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

使用正则表达式删除java中括号中的所有内容,java,regex,Java,Regex,我使用了下面的正则表达式试图删除括号以及名为name的字符串中的所有内容 name.replaceAll("\\(.*\\)", ""); 出于某种原因,这是保持名称不变。我做错了什么?不编辑原始字符串,但返回新字符串。所以你需要做: name = name.replaceAll("\\(.*\\)", ""); 如果阅读,您会注意到它指定结果字符串是返回值 更一般地说,Strings在Java中是不可变的;它们从不改变值。字符串是不可变的。你必须这样做: name = name.repla

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

name.replaceAll("\\(.*\\)", "");
出于某种原因,这是保持名称不变。我做错了什么?

不编辑原始字符串,但返回新字符串。所以你需要做:

name = name.replaceAll("\\(.*\\)", "");
如果阅读,您会注意到它指定结果字符串是返回值


更一般地说,
String
s在Java中是不可变的;它们从不改变值。

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

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

编辑:另外,由于
*
是贪婪的,它会尽可能多地杀戮。因此,正如Jelvis提到的那样,“.*”选择所有内容并将“(ab)ok(cd)”转换为“”。”

下面的版本在这些情况下工作“(ab)ok(cd)”->“ok”,方法是选择除右括号外的所有内容并删除空格

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

我正在使用这个函数:

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

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

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

在科特林,我们必须使用toRegex

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

事实上,正如我想的那样,嵌套不会成为问题,因为默认情况下,
*
是贪婪的。真正的问题是像
(abc)(def)
这样的字符串将被完全删除。在我的情况下也不是问题。括号永远不会超过一组。当
test=“(文本(多一些文本)然后多一些)”时,此操作将失败。