方法java.time.Matcher.matches()将给定区域与指定模式进行匹配。如果区域序列与Matcher的模式匹配,则返回true,否则返回false。
一个程序演示了Java正则表达式中的Matcher.matches()方法,如下所示-
示例import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String args[]) {
Pattern p = Pattern.compile("Apple");
String str1 = "apple";
String str2 = "Apple";
String str3 = "APPLE";
Matcher m1 = p.matcher(str1);
Matcher m2 = p.matcher(str2);
Matcher m3 = p.matcher(str3);
System.out.println(str1 + " matches? " + m1.matches());
System.out.println(str2 + " matches? " + m2.matches());
System.out.println(str3 + " matches? " + m3.matches());
}
}
输出结果
上面程序的输出如下-apple matches? false
Apple matches? true
APPLE matches? false
现在让我们了解上面的程序。
使用该matches()方法,将各种Matcher模式与原始模式“ Apple”进行比较,并打印返回的值。演示这的代码片段如下-Pattern p = Pattern.compile("Apple");
String str1 = "apple";
String str2 = "Apple";
String str3 = "APPLE";
Matcher m1 = p.matcher(str1);
Matcher m2 = p.matcher(str2);
Matcher m3 = p.matcher(str3);
System.out.println(str1 + " matches? " + m1.matches());
System.out.println(str2 + " matches? " + m2.matches());
System.out.println(str3 + " matches? " + m3.matches());