Method matches()
checks whether the String is matching with the specified regular expression. If the String fits in the specified regular expression then this method returns true else it returns false. Below is the syntax of the method:
public boolean matches(String regex)
It throws PatternSyntaxException
– if the specified regular expression is not valid.
Example: matches() method
In this example we have a String and three regular expressions. We are matching the regular expressions(regex) with the input String using the matches()
method.
public class MatchesExample{ public static void main(String args[]){ String str = new String("Java String Methods"); System.out.print("Regex: (.*)String(.*) matches string? " ); System.out.println(str.matches("(.*)String(.*)")); System.out.print("Regex: (.*)Strings(.*) matches string? " ); System.out.println(str.matches("(.*)Strings(.*)")); System.out.print("Regex: (.*)Methods matches string? " ); System.out.println(str.matches("(.*)Methods")); } }
Output:
Regex: (.*)String(.*) matches string? true Regex: (.*)Strings(.*) matches string? false Regex: (.*)Methods matches string? true
Leave a Reply