-3

我查看了一个堆栈溢出,它给了我这个正则表达式——str.replaceAll("\\(^()*\\)", "");但是当我运行它时,它实际上并没有做任何事情。那么如何从给定的字符串中删除括号内的任何部分,包括括号?另外:除了括号之外,字符串中只能出现字母和空格。不要担心“[]”和“{}”等其他括号,因为它们不包括在内,如果它们出现,我不想触摸“[]”和“{}”。我只想删除括号和括号内的内容。帮助将不胜感激。这还包括多个括号和嵌套括号。

    public static String removeParentheses(final String str) {
        str.replaceAll("\\(^()*\\)", "");
        System.out.println(str);
            return str; // your code here
        }
       public static void main(String[] args) {
            String str= "example(unwanted thing)example";
            removeParentheses(str);
}
    ```
expected result is "exampleexample" but actual result was: "example(unwanted thing)example" which is not what I wanted.
I already searched stack overflow for help and found one place but it didn't help me.
help would be appreciated.
4

1 回答 1

1

更正了 2 个问题

  1. 打印不正确的变量
  2. 正则表达式
    public static void main(String[] args) {
        removeParentheses2("example(unwanted thing)example");
        removeParentheses2("abc(123)def(456)ghi");
        removeParentheses2("abc (123) def (456) ghi");
        removeParentheses2("abc(1|3)def(4^6)gh");
        removeParentheses2("abc(((1|3)def(4^6)gh))");

    }

    public static String removeParentheses(final String str) {
        String updated = str.replaceAll("\\([^()]*\\)", "");
        if (updated.contains("(")) updated = removeParentheses(updated);
        System.out.println(str + " >> " + updated);
        return updated;
    }


    // a more direct regex - no loop
    static final String regex = "\\([^()]*\\)";
    static final String regex_match = "\\([" + regex + "]*\\)";
    public static String removeParentheses2(final String str) {
        String updated = str.replaceAll(regex_match, "");
        System.out.println(str + " >> " + updated);
        return updated;
    }



example(unwanted thing)example >> exampleexample
abc(123)def(456)ghi >> abcdefghi
abc (123) def (456) ghi >> abc  def  ghi
abc(1|3)def(4^6)gh >> abcdefgh
abc(defgh) >> abc
abc((1|3)def(4^6)gh) >> abc
于 2020-11-15T06:09:12.013 回答