Java 正则表达式中 Matcher.matches() 方法的角色
方法 java.time.Matcher.matches() 根据指定模式匹配给定的区域。如果区域序列与 Matcher 的模式匹配,则该方法返回真,否则返回假。
一个展示 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());
广告
数据结构
网络技术
关系型数据库
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP