正則表達式定義字串模式,用於搜尋、編輯、處理文字。Java 實作 (java.util.regex) 與 Perl 高度相似。
Pattern.compile(regex) 取得實例。pattern.matcher(input) 取得。用括號 () 將多字元視為單一單元。從左至右按開括號編號:
正則:((A)(B(C))) 群組 0:整個表達式 ((A)(B(C))) 群組 1:(A) 群組 2:(B(C)) 群組 3:(C)
matcher.groupCount() 返回捕獲群組數(不含群組 0)。group(0) 代表整個匹配。
String line = "This order was placed for QT3000! OK?";
String pattern = "(\\D*)(\\d+)(.*)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find()) {
System.out.println("Full: " + m.group(0));
System.out.println("Group1: " + m.group(1)); // 非數字前綴
System.out.println("Group2: " + m.group(2)); // 數字部分
}
// 輸出:
// Full: This order was placed for QT3000! OK?
// Group1: This order was placed for QT
// Group2: 3000
| 字元/結構 | 說明 |
|---|---|
\ | 轉義字元,如 \n 換行、\\ 反斜線 |
^ | 行首(多行模式下匹配 \n/\r 後) |
$ | 行尾(多行模式下匹配 \n/\r 前) |
* | 零次或多次 {0,} |
+ | 一次或多次 {1,} |
? | 零次或一次 {0,1} |
{n} | 恰好 n 次 |
{n,} | 至少 n 次 |
{n,m} | n 到 m 次 |
? (貪婪修飾) | 緊跟限定符後,改為非貪婪模式(如 *?、+?) |
. | 任意單一字元(除換行) |
(pattern) | 捕獲群組 |
(?:pattern) | 非捕獲群組 |
(?=pattern) | 正向前瞻 |
(?!pattern) | 負向前瞻 |
x|y | x 或 y |
[xyz] | 字元集合 |
[^xyz] | 排除字元集合 |
[a-z] | 字元範圍 |
\d | 數字 [0-9] |
\D | 非數字 [^0-9] |
\s | 空白字元 |
\S | 非空白字元 |
\w | 單字字元 [A-Za-z0-9_] |
\W | 非單字字元 |
\b | 單字邊界 |
\B | 非單字邊界 |
Java 字串雙重轉義: Java 原始碼中反斜線需寫兩個:"\\b"才代表正則的\b(單字邊界),"\\d+"代表\d+。
start() / start(group):匹配/群組起始索引end() / end(group):匹配/群組結束索引(最後字元索引+1)find() / find(start):尋找下一個匹配子序列matches():整個區域完全匹配lookingAt():從區域開頭嘗試匹配(不要求完整)replaceAll(replacement):替換所有匹配replaceFirst(replacement):替換首個匹配appendReplacement(sb, replacement) / appendTail(sb):非終端/終端追加替換,構建新字串quoteReplacement(s):返回字面替換字串(處理 $、\ 等特殊字元)String REGEX = "\\bcat\\b";
String INPUT = "cat cat cat cattie cat";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT);
int count = 0;
while (m.find()) {
System.out.println("Match " + ++count + ": start=" + m.start() + ", end=" + m.end());
}
// 輸出:4 次匹配,cattie 不匹配(邊界限制)
String REGEX = "foo";
String INPUT = "fooooooooooooooooo";
Matcher m = Pattern.compile(REGEX).matcher(INPUT);
System.out.println("lookingAt: " + m.lookingAt()); // true
System.out.println("matches: " + m.matches()); // false(需完整匹配)
String INPUT = "The dog says meow. All dogs say meow.";
System.out.println(Pattern.compile("dog").matcher(INPUT).replaceAll("cat"));
// The cat says meow. All cats say meow.
String REGEX = "a*b";
String INPUT = "aabfooaabfooabfoob";
StringBuffer sb = new StringBuffer();
Matcher m = Pattern.compile(REGEX).matcher(INPUT);
while (m.find()) m.appendReplacement(sb, "-");
m.appendTail(sb);
System.out.println(sb); // -foo-foo-foo-
捕獲語法錯誤並診斷:
getDescription():錯誤描述getIndex():錯誤位置索引getPattern():錯誤的正則模式getMessage():多行詳細錯誤資訊善用正則表達式能大幅簡化複雜文字處理邏輯,但需注意效能與可讀性平衡。