10

I've used the following regex to try to remove parentheses and everything within them in a string called name.

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

For some reason, this is leaving name unchanged. What am I doing wrong?

7 Answers 7

33

Strings are immutable. You have to do this:

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

Edit: Also, since the .* is greedy, it will kill as much as it can. So "(abc)something(def)" will be turned into "".

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, as I think about it a bit more, nesting won't be an issue because the .* is greedy by default. The real issue is with strings like (abc) (def) which will be deleted completely.
Also not a problem in my situation. There will never be more than one set of parentheses.
11

As mentionend by by Jelvis, ".*" selects everything and converts "(ab) ok (cd)" to ""

The version below works in these cases "(ab) ok (cd)" -> "ok", by selecting everything except the closing parenthesis and removing the whitespaces.

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

1 Comment

This fails when test="(text(some more text ) then some more )".
4

String.replaceAll() doesn't edit the original string, but returns the new one. So you need to do:

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

Comments

2

If you read the Javadoc for String.replaceAll(), you'll notice that it specifies that the resulting string is the return value.

More generally, Strings are immutable in Java; they never change value.

Comments

2

I'm using this function:

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

You can call it like this:

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

Comments

1

To get around the .* removing everything in between two sets of parentheses you can try :

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

Comments

0

In Kotlin we must use toRegex.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.