Java String matches() method example

java.lang.String matches()

Description :

This java tutorial shows how to use the matches() method of java.lang.String class. This method returns a boolean datatype which which is a result in testing if our regex pattern matches that of our String. This method is exactly give the same on calling the method Pattern.matches(regex,str).

Method Syntax :

public boolean matches(String regex)

Parameter Input :

DataType Parameter Description
String regex the regex pattern we want to check with our String

Method Returns :

This method returns a boolean datatype which corresponds to the pattern matching of the regex String argument to our String object. Returns true if the patter argument matches that of our String otherwise it is false.

Compatibility Version :

Since the beginning

Exception :

N/A

Discussion :

I would not go much on the deeper knowledge of pattern matching on this tutorial because it merits a new article for Regular Expression. I will cover only the basic knowledge on this topic.

Like for example we have a String “test.doc” and we want to check if our String ends with .doc. As you would already have noticed this is helpful in listing only the filenames that is having extension of .doc.

On Unix we do ls -ltr *.doc to list down all files ending with .doc. Same principle in java, we will be using the same trick. Lets take for an example

The output will be true on the example that I have provided above since the second element of our String array ends with .doc regardless of characters as a prefix on our String object. The .* character signifies all in literal interpretation. So the expression String.matches(“.*.doc”), is like saying give me an output of true if String ends with .doc regardless what are the characters before that suffix.

Java Code Example :

This example source code demonstrates the use of matches() method of String class. First and foremost we have separated the method in getting the filenames from our directory to be able to segregate the implementation from our target example which is to use the matches() method. The output of our method is an array of String filenames and then we use the matches method of String class to check for files that is ending with .docx.

Sample Output :

Running the matches() method example source code of java.lang.String class will give you the following output 

Suggested Reading List :

Comments are closed