簡體   English   中英

使用正則表達式刪除括號中的所有內容java

[英]Remove everything in parentheses java using regex

我使用以下正則表達式嘗試刪除名為name的字符串中的括號及其中的所有內容。

name.replaceAll("\\(.*\\)", "");

出於某種原因,這使名稱保持不變。 我究竟做錯了什么?

字符串是不可變的。 你必須這樣做:

name = name.replaceAll("\\(.*\\)", "");

編輯:另外,由於.*是貪婪的,它會盡可能多地殺死。 所以"(abc)something(def)"將變成""

正如 Jelvis 所提到的,".*" 選擇所有內容並將 "(ab) ok (cd)" 轉換為 ""

下面的版本適用於這些情況“(ab) ok (cd)”->“ok”,通過選擇除右括號之外的所有內容並刪除空格。

test = test.replaceAll("\\s*\\([^\\)]*\\)\\s*", " ");

String.replaceAll()不會編輯原始字符串,而是返回新字符串。 所以你需要這樣做:

name = name.replaceAll("\\(.*\\)", "");

我正在使用這個功能:

public static String remove_parenthesis(String input_string, String parenthesis_symbol){
    // removing parenthesis and everything inside them, works for (),[] and {}
    if(parenthesis_symbol.contains("[]")){
        return input_string.replaceAll("\\s*\\[[^\\]]*\\]\\s*", " ");
    }else if(parenthesis_symbol.contains("{}")){
        return input_string.replaceAll("\\s*\\{[^\\}]*\\}\\s*", " ");
    }else{
        return input_string.replaceAll("\\s*\\([^\\)]*\\)\\s*", " ");
    }
}

你可以這樣稱呼它:

remove_parenthesis(g, "[]");
remove_parenthesis(g, "{}");
remove_parenthesis(g, "()");

如果您閱讀String.replaceAll()Javadoc ,您會注意到它指定結果字符串是返回值

更一般地說, String在 Java 中是不可變的; 他們永遠不會改變價值。

要繞過.*刪除兩組括號之間的所有內容,您可以嘗試:

name = name.replaceAll("\\(?.*?\\)", "");

在 Kotlin 中,我們必須使用 toRegex。

val newName = name.replace("\\(?.*?\\)".toRegex(), "");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM