Replace all "(" and ")" in a string in Java

Neeraj picture Neeraj · Sep 12, 2012 · Viewed 35.2k times · Source

How to replace all "(" and ")" in a string with a fullstop, in Java? I tried in the following way:

String url = "https://bitbucket.org/neeraj_r/url-shortner)";
url.replaceAll(")", ".");
url.replaceAll(")", ".");

But it does not work. The error is:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unmatched closing
')'
 )
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
at com.azzist.cvConversion.server.URLChecker.main(URLChecker.java:32)

I think this problem will be there in all regex too. Adding \ before ) did not work.

Answer

beny23 picture beny23 · Sep 12, 2012

You can use replaceAll in one go:

url.replaceAll("[()]", ".")

Explanation:

  • [()] matches both ( and ), the brackets don't need to be escaped inside the [] group.

EDIT (as pointed out by @Keppil):

Note also, the String url is not changed by the replace, it merely returns a new String with the replacements, so you'd have to do:

url = url.replaceAll("[()]", ".");