首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java 正則表達式完整教學:Pattern、Matcher 與實戰範例

     編輯:Java 程式設計入門

Java 正則表達式完整教學:Pattern、Matcher 與實戰範例

正則表達式定義字串模式,用於搜尋、編輯、處理文字。Java 實作 (java.util.regex) 與 Perl 高度相似。

核心三大類別

  • Pattern: 編譯後的正則表示物件。無公共建構子,靜態方法 Pattern.compile(regex) 取得實例。
  • Matcher: 執行匹配操作的引擎。由 pattern.matcher(input) 取得。
  • PatternSyntaxException: 非受檢異常,表示正則語法錯誤。

捕獲群組

用括號 () 將多字元視為單一單元。從左至右按開括號編號:

正則:((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|yx 或 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+。

Matcher 核心方法分類

索引方法

  • start() / start(group):匹配/群組起始索引
  • end() / end(group):匹配/群組結束索引(最後字元索引+1)

搜尋/匹配方法

  • find() / find(start):尋找下一個匹配子序列
  • matches():整個區域完全匹配
  • lookingAt():從區域開頭嘗試匹配(不要求完整)

替換方法

  • replaceAll(replacement):替換所有匹配
  • replaceFirst(replacement):替換首個匹配
  • appendReplacement(sb, replacement) / appendTail(sb):非終端/終端追加替換,構建新字串
  • quoteReplacement(s):返回字面替換字串(處理 $、\ 等特殊字元)

實戰範例集錦

1. 計算單字出現位置

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 不匹配(邊界限制)

2. matches vs lookingAt

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(需完整匹配)

3. 替換所有/首次匹配

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.

4. 進階替換:appendReplacement / appendTail

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-

PatternSyntaxException 處理

捕獲語法錯誤並診斷:

  • getDescription():錯誤描述
  • getIndex():錯誤位置索引
  • getPattern():錯誤的正則模式
  • getMessage():多行詳細錯誤資訊

善用正則表達式能大幅簡化複雜文字處理邏輯,但需注意效能與可讀性平衡。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved