字符串 "<工作>fgdfg<學習>iop<生活>" 中需提取尖括號包裹的標籤:工作、學習、生活。
String text = "<工作>fgdfg<學習>iop<生活>";
// 正則:(?<=<).*?(?=>)
// 解析:(?<=<) 正向後顧斷言,匹配 < 後的位置
// .*? 非貪婪匹配任意字符
// (?=>) 正向先行斷言,匹配 > 前的位置
Pattern pattern = Pattern.compile("(?<=<).*?(?=>)");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
// 輸出:工作、學習、生活
}
// 更直觀,性能略優
Pattern pattern = Pattern.compile("<(.*?)>");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group(1)); // 組1為括號內容
}
| 輸入 | 輸出 | 說明 |
|---|---|---|
<a><b> | a, b | 連續標籤 |
<a></b> | a, /b | 包含斜杠 |
<> | (空) | 空標籤匹配空串 |
無標籤文本 | (無) | 無匹配不報錯 |
<未閉合 | (無) | 需>結束 |
.*? 防止跨標籤匹配若處理標準標記語言,**請使用專用解析器**(Jsoup, DOM, SAX),正則無法正確處理嵌套、屬性、註釋、CDATA 等複雜結構。
掌握零寬斷言與捕獲組兩種提取模式,靈活應對各類定界符提取需求。