使用正则表达式删除括号中的所有内容

时间:2011-11-21 00:47:12

标签: java regex

我使用以下正则表达式尝试在名为name的字符串中删除括号及其中的所有内容。

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

出于某种原因,这是保持名称不变。我做错了什么?

7 个答案:

答案 0 :(得分:23)

字符串是不可变的。你必须这样做:

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

编辑:此外,由于.*贪婪,它会尽可能多地杀死它。因此"(abc)something(def)"将变为""

答案 1 :(得分:8)

正如Jelvis所提到的,“。*”选择所有内容并将“(ab)ok(cd)”转换为“”

以下版本适用于这些情况“(ab)ok(cd)” - > “ok”,通过选择除右括号之外的所有内容并删除空格。

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

答案 2 :(得分:3)

String.replaceAll()不会编辑原始字符串,但会返回新字符串。所以你需要这样做:

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

答案 3 :(得分:2)

如果您阅读Javadoc for String.replaceAll(),您会注意到它指定结果字符串是返回值

更一般地说,String在Java中是不可变的;他们永远不会改变价值。

答案 4 :(得分:1)

我正在使用此功能:

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, "()");

答案 5 :(得分:1)

要绕过.*,请删除两组括号之间的所有内容,您可以尝试:

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

答案 6 :(得分:0)

在Kotlin中,我们必须使用toRegex。

val newName = name.replace("\\(?.*?\\)".toRegex(), "");
相关问题