Home > database >  How to remove every sequence of "()" in a string in java?
How to remove every sequence of "()" in a string in java?

Time:01-04

I'm trying to remove every sequence of () in my string. For example my String is:

String a = "() a)";

And I want it to become " a)"

When I tried this it gave me an infinite loop

    public static String removeParentheses(String s) {
        while (s.contains("()")) {
            s = s.replaceAll("()", "");
        }
        return s;
    }

CodePudding user response:

String replaceAll method require regexp in parameter. In your case you provide empty group. To use string as parameter you can use replace method like:

public static void main(String[] args) {
        String toChange = "asa()assaa()ass()asa()";
        String result = toChange.replace("()", "");
        assert Objects.equals(result, "asaassaaassasax");
}

Or change the regexp to correct form using \ character in way:

public static void main(String[] args) {
     String toChange = "asa()assaa()ass()asa()";
     String result = toChange.replaceAll("\\(\\)", "");
     assert Objects.equals(result, "asaassaaassasax");
}

CodePudding user response:

According the documentation of String.replaceAll, the first argument is a regular expression.

This means () is not being treated literally, it's being treated as an empty capture group, which effectively matches nothing. I think what you're looking for is the normal String.replace method. I'm aware that the names of these methods seem to imply that replace only replaces one instance while replaceAll replaces all of them, but this is not the case.

public static String removeParentheses(String s) {
    return s.replace("()", "");
}

JDoodle deomonstrating code above

If for some reason you would like to continue using replaceAll instead, you can dynamically escape the pattern using Pattern.quote.

public static String removeParentheses(String s) {
    String pattern = Pattern.quote("()");
    return s.replaceAll(pattern, "");
}

JDoodle demonstrating code above

  •  Tags:  
  • java
  • Related