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