在 Java 正則表示式中使用字元類
字元類是一組用方括號括起來的字元。字元類中的字元指定可以與輸入字串中的字元匹配才能成功的字元。字元類的示例是 [a-z],它表示從 a 到 z 的字母。
以下展示了一個有關 Java 正則表示式中使用字元類的程式
示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String args[]) {
Pattern p = Pattern.compile("[a-z]+");
Matcher m = p.matcher("the sky is blue");
System.out.println("The input string is: the sky is blue");
System.out.println("The Regex is: [a-z]+");
System.out.println();
while (m.find()) {
System.out.println("Match: " + m.group());
}
}
}輸出
The input string is: the sky is blue The Regex is: [a-z]+ Match: the Match: sky Match: is Match: blue
現在讓我們來理解以上程式。
在字串序列“the sky is blue” 中查詢子序列 “[a-z]+”。此處使用字元類 [a-z],它表示從 a 到 z 的字母。find() 方法用於查詢子序列是否在輸入序列中,然後列印所需結果。以下是一個展示此操作的程式碼片段
Pattern p = Pattern.compile("[a-z]+");
Matcher m = p.matcher("the sky is blue");
System.out.println("The input string is: the sky is blue");
System.out.println("The Regex is: [a-z]+");
System.out.println();
while (m.find()) {
System.out.println("Match: " + m.group());
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP