使用 Java 正則表示式處理簡單組
使用 Java 正則表示式中的組,多個字元可以作為單個單元處理。方法 java.time.Matcher.group() 用於查詢輸入序列字串中與所需模式匹配的子序列。
一個展示 Java 正則表示式中組的程式如下 −
示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String args[]) {
Pattern p = Pattern.compile("\w\d");
Matcher m = p.matcher("I am f9");
System.out.println("The input string is: I am f9");
System.out.println("The Regex is: \w\d");
System.out.println();
if (m.find()) {
System.out.println("Match: " + m.group());
}
}
}上述程式的輸出如下 −
The input string is: I am f9 The Regex is: \w\d Match: f9
現在讓我們來理解上述程式。
在字串序列 "I am f9" 中搜索子序列 “\w\d”。使用 find() 方法查詢該子序列是否在輸入序列中,並使用 group() 方法列印所需結果。一個展示它的程式碼片段如下 −
Pattern p = Pattern.compile("\w\d");
Matcher m = p.matcher("I am f9");
System.out.println("The input string is: I am f9");
System.out.println("The Regex is: \w\d");
System.out.println();
if (m.find()) {
System.out.println("Match: " + m.group());
}
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP