Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove everything in parentheses java using regex

Tags:

java

regex

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?

like image 391
Daniel Avatar asked Nov 21 '11 00:11

Daniel


People also ask

How do you remove parentheses in Java?

There are two ways in which you can remove the parentheses from a String in Java. You can traverse the whole string and append the characters other than parentheses to the new String. You can use the replaceAll() method of the String class to remove all the occurrences of parentheses.

How do you use parentheses in regex?

By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex. Only parentheses can be used for grouping.

How do you remove all brackets from a string?

Brackets can be removed from a string in Javascript by using a regular expression in combination with the . replace() method.


3 Answers

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 "".

like image 149
Tikhon Jelvis Avatar answered Oct 21 '22 23:10

Tikhon Jelvis


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*", " ");
like image 28
Pascalius Avatar answered Oct 21 '22 23:10

Pascalius


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

name = name.replaceAll("\\(.*\\)", "");
like image 23
jli Avatar answered Oct 22 '22 01:10

jli