w3resource logo


Introduction to Java Programming

Java String: matches() Method

Secondary Nav

public boolean matches(String regex)

The matches() method tells whether or not this string matches the given regular expression.

An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression

Pattern.matches(regex, str)

Java Platform: Java SE 8

Syntax :

matches(String regex)

Parameter :

Name Description Type
regex the regular expression to which this string is to be matched boolean

Return Value : true if, and only if, this string matches the given regular expression.

Return Value Type: boolean

Throws:
PatternSyntaxException - if the regular expression's syntax is invalid

Example : Java String matches(String regex) Method

The following example shows the usage of java String() method.

public class MatchesExample {
   public static void main(String args[]){
       String str = new String("The quick brown fox jumps over the lazy dog.");
       System.out.println();
       System.out.print("Regex: (.*)quick brown fox(.*) " );
       System.out.println(str.matches("(.*)quick brown fox(.*)"));

       System.out.print("Regex: (.*)quick brown wolf(.*) " );
       System.out.println(str.matches("(.*)quick brown wolf(.*)"));
       System.out.println();
       
   }
}

Output:

Regex: (.*)quick brown fox(.*) true                    
Regex: (.*)quick brown wolf(.*) false 

Java Code Editor :







Join our Question Answer community to learn and share your programming knowledge.

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number