字串含 [Brochures] Title、[Thought Leadership] Something,需移除方括號及其內容,保留後續文本。
String input = "[Brochures] This is a brochure title [Thought Leadership] This is something else";
String output = input.replaceAll("\\[.*?\\]", "");
// 結果:" This is a brochure title This is something else"
| 部分 | 含義 |
|---|---|
\\[ | 匹配字面字符 [(需轉義) |
.*? | **非貪婪**匹配任意字符(除換行),盡可能少 |
\\] | 匹配字面字符 ] |
非貪婪 ?* 關鍵:若用貪婪 .*,會從第一個 [ 匹配到最後一個 ],錯誤吞掉中間文本。
// 移除括號,保留內容
String keepContent = input.replaceAll("\\[(.*?)\\]", "$1");
// "[Brochures] Title" → "Brochures Title"
public static String removeBracketedContent(String text) {
if (text == null) return null;
return text.replaceAll("\\[.*?\\]", "").trim(); // 移除後去首尾空格
}
// 測試
String[] tests = {
"[Brochures] Title",
"Prefix [Tag] Middle [Tag2] Suffix",
"No brackets here",
"[Nested [inner] outer]" // 非貪婪匹配到第一個 ]
};
for (String t : tests) {
System.out.println(removeBracketedContent(t));
}
Title
Prefix Middle Suffix
No brackets here
outer] // 注意:嵌套括號正則無法完美處理,需解析器
replaceAll("\\[.*?\\]", "") 簡潔移除方括號及其內容。關鍵:**非貪婪 .*?** 防止跨多組括號匹配。嵌套括號場景正則無能為力,需狀態機解析器。