首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 正則表達式移除字串中方括號及其內容:\\[.*?\\]

     編輯:程式設計綜合問答

需求

字串含 [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"

Java 完整示例


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("\\[.*?\\]", "") 簡潔移除方括號及其內容。關鍵:**非貪婪 .*?** 防止跨多組括號匹配。嵌套括號場景正則無能為力,需狀態機解析器。

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