Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 373
Neeraj Avatar asked Sep 12 '12 08:09

Neeraj


2 Answers

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("[()]", ".");
like image 109
beny23 Avatar answered Oct 13 '22 18:10

beny23


You need to escape '(' and ')' with "\\(" and "\\)" respectively:

url = url.replaceAll("\\)", ".");  
url = url.replaceAll("\\(", ".")
like image 29
munyengm Avatar answered Oct 13 '22 17:10

munyengm