Replace all "(" and ")" in a string in Java
Solution 1
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("[()]", ".");
Solution 2
You need to escape '('
and ')'
with "\\("
and "\\)"
respectively:
url = url.replaceAll("\\)", ".");
url = url.replaceAll("\\(", ".")
Solution 3
replaceAll()
expects a regex
as first parameter, and parantheses have special meaning there.
use replace()
instead:
String url = "https://bitbucket.org/neeraj_r/url-shortner)";
url = url.replace("(", ".").replace(")", ".");
Note that the url =
part is important to save the result of the replacement. Since String
s are immutable, the original String
isn't changed, but a new one is created. To keep the result url
needs to point to this one instead.
Solution 4
- String is immutable.
-
)
should be escaped with 2 backslashes.
So the code would look like this:
String url = "https://bitbucket.org/neeraj_r/url-shortner)";
// is you need to escape all of them, use "[()]" pattern, instead of "\\)"
String s = url.replaceAll("\\)", ".");
System.out.println(url);
System.out.println(s);
And the output:
https://bitbucket.org/neeraj_r/url-shortner)
https://bitbucket.org/neeraj_r/url-shortner.
Solution 5
Adding a single \
will not work, because that will try to evaluate \)
as an escaped special character which it isn't.
You'll need to use "\)". The first \
escapes the second, producing a "normal" \
, which in turn escapes the )
, producing a regex matching exactly a closing paranthesis )
.
The general purpose solution is to use Pattern.quote
, which takes an arbitrary string and returns a regex that matches exactly that string.
![Neeraj](https://i.stack.imgur.com/0i11K.jpg?s=256&g=1)
Comments
-
Neeraj almost 4 years
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.