Remove everything in java parentheses with regex

I used the following regular expression to try to remove the parentheses and everything inside them in a string named name .

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

For some reason this leaves the name unchanged. What am I doing wrong?

+7
source share
5 answers

Lines are immutable. You must do this:

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

Edit: Also, since .* Is greedy, it will kill as much as possible. So, "(abc)(def)" will be converted to "" .

+18
source

As Jelvis mentions, ". *" Selects everything and converts "(ab) ok (cd)" to ""

The next version works in these cases "(ab) ok (cd)" β†’ "ok", selecting everything except the closing brackets and removing the spaces.

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

String.replaceAll() does not edit the original string, but returns a new one. So you need to do:

 name = name.replaceAll("\\(.*\\)", ""); 
+2
source

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

In general, String immutable in Java; they never change meaning.

+2
source

I am 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, "()"); 
0
source

All Articles