JAVA中正則表達式的入門與使用
一,基礎概念
正則表達式(Regex) 用于匹配字符串中的特定模式,Java 中通過 java.util.regex 包實現,核心類為:
Pattern:編譯后的正則表達式對象。
Matcher:用于在輸入字符串中查找匹配項。
二,如何快速入門
1,編譯正則表達式
Pattern pattern = Pattern.compile("你的正則表達式");
2,創建匹配器
Matcher matcher = pattern.matcher("要匹配的字符串");
3,執行匹配
常用方法:
- find():查找下一個匹配項。
- matches():檢查整個字符串是否匹配。
- group():獲取匹配的子字符串。
三,核心語法
1,基本元字符
元字符 | 含義 | 示例 |
---|---|---|
. | 匹配任意單個字符(換行除外) | “a.c” 匹配 “abc”, “a2c” |
^ | 匹配字符串開頭 | “^hello” 匹配 “hello…” |
$ | 匹配字符串結尾 | “world$” 匹配 “…world” |
* | 匹配前面的元素 0次或多次 | “a*” 匹配 “”, “a”, “aaa” |
+ | 匹配前面的元素 1次或多次 | “a+” 匹配 “a”, “aaa” |
? | 匹配前面的元素 0次或1次 | “a?” 匹配 “”, “a” |
[ ] | 匹配字符集中的任意一個字符 | [abc] 匹配 “a”, “b”, “c” |
| | 邏輯或(匹配左側或右側) | “cat|dog” 匹配 “cat"或"dog” |
2,量詞與分組
- 量詞:{n}(n次)、{n,}(至少n次)、{n,m}(n到m次) 示例:“a{2}” 匹配 “aa”。
- 分組:(…) 將子表達式分組,可用于捕獲或引用。 示例:“(\d{3})-(\d{4})” 捕獲電話號碼的區號和號碼。
3,預定義字符類
字符類 | 含義 |
---|---|
\d | 匹配數字(0-9) |
\D | 匹配非數字 |
\w | 匹配字母、數字、下劃線 |
\W | 匹配非單詞字符 |
\s | 匹配空白字符(空格、換行) |
\S | 匹配非空白字符 |
四、場景應用
1,驗證郵箱格式
String email = "user@example.com";
Pattern pattern = Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
Matcher matcher = pattern.matcher(email);
boolean isValid = matcher.matches(); // true 或 false
2,提取電話號碼
String text = "電話:138-1234-5678";
Pattern pattern = Pattern.compile("\\d{3}-\\d{4}-\\d{4}");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {System.out.println(matcher.group()); // 輸出 "138-1234-5678"
}
3,替換字符串
String text = "價格:$99.99";
Pattern pattern = Pattern.compile("\\$\\d+\\.\\d{2}");
Matcher matcher = pattern.matcher(text);
String replaced = matcher.replaceAll("¥100.00"); // 替換為 ¥100.00
4, 分割字符串
String csv = "apple,banana,cherry";
String[] fruits = csv.split(","); // 輸出 ["apple", "banana", "cherry"]
五、正則使用tips
1,轉義字符
在 Java 字符串中,反斜杠 \ 需要轉義為 \。
示例:正則表達式 \d 在代碼中寫為 “\d”。
2,性能優化
頻繁使用正則時,建議預編譯 Pattern 對象:
private static final Pattern EMAIL_PATTERN = Pattern.compile("...");
3,邊界匹配
使用 ^ 和 $ 確保匹配整個字符串,而非子串:
例如"^start" 匹配以 “start” 開頭的字符串,“end$” 匹配以 “end” 結尾的字符串。
4,分組捕獲
使用 () 分組,通過 group(int) 獲取子匹配結果:
Pattern pattern = Pattern.compile("(\\d{3})-(\\d{4})");Matcher matcher = pattern.matcher("123-4567");System.out.println(matcher.group(1)); // 輸出 "123"