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?
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.
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.
Brackets can be removed from a string in Javascript by using a regular expression in combination with the . replace() method.
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 ""
.
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*", " ");
String.replaceAll()
doesn't edit the original string, but returns the new one. So you need to do:
name = name.replaceAll("\\(.*\\)", "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With