原文: https://beginnersbook.com/2013/12/java-string-matches-method-example/
方法matches()检查String是否与指定的正则表达式匹配。如果String适合指定的正则表达式,则此方法返回true,否则返回false。以下是该方法的语法:
public boolean matches(String regex)它会抛出PatternSyntaxException - 如果指定的正则表达式无效。
在这个例子中,我们有一个String和三个正则表达式。我们使用matches()方法将正则表达式(regex)与输入String进行匹配。
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"));
}
}输出:
Regex: (.*)String(.*) matches string? true
Regex: (.*)Strings(.*) matches string? false
Regex: (.*)Methods matches string? true