Java 通過 java.util.regex 包提供正則表達式支持,核心類包括:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class REMatch {
public static void main(String[] args) {
String patt = "Q[^u]\\d+\\."; // Q 後非 u,接數字,以點結尾
Pattern r = Pattern.compile(patt);
String line = "Order QT300. Now! QT400.";
Matcher m = r.matcher(line);
while (m.find()) {
// group(0) 返回完整匹配;group(i) 返回第 i 組
System.out.println(patt + " matches \"" + m.group(0) + "\" in \"" + line + "\"");
System.out.println("start:" + m.start() + " end:" + m.end());
}
}
}
Q[^u]\d+\. matches "QT300." in "Order QT300. Now! QT400." start:6 end:12 Q[^u]\d+\. matches "QT400." in "Order QT300. Now! QT400." start:18 end:24
m.find():尋找下一個匹配子序列,返回 booleanm.group(0):完整匹配內容m.start() / m.end():匹配在原字符串中的起止索引Q[^u]\d+\.:Q 開頭、第二字符非 u、接一位或多位數字、以點結尾import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class REMatchTwoFields {
public static void main(String[] args) {
String inputLine = "Adams,John Quincy";
Pattern r = Pattern.compile("(.*),(.*)"); // 兩個捕獲組
Matcher m = r.matcher(inputLine);
if (!m.matches()) { // matches() 要求整個字符串匹配
throw new IllegalArgumentException("Bad Input");
}
// groupCount() 返回捕獲組數量,group(0) 為整個輸入
for (int i = 0; i < m.groupCount() + 1; i++) {
System.out.println("分組" + i + ":" + m.group(i));
}
}
}
分組0:Adams,John Quincy 分組1:Adams 分組2:John Quincy
matches():整串匹配;find():部分匹配group(int group):獲取指定組內容,group() 等同 group(0)(?<name>pattern),配合 m.group("name")| 符號 | 含義 |
|---|---|
. | 任意字符(除換行) |
\d | 數字 [0-9] |
\w | 單詞字符 [a-zA-Z0-9_] |
\s | 空白字符 |
^ | 行首 / 字符類取反 |
$ | 行尾 |
* + ? | 量詞:0或多、1或多、0或1 |
() | 捕獲組 |
(?:) | 非捕獲組 |
熟練掌握 Pattern/Matcher 配合正則語法,能高效完成字符串解析、驗證、提取等核心任務。