1

I can't seem to replace a string of ":)" to something else, here is my code:

if(message.contains(":)")) message = message.replaceAll(":)", replacement);

This is the error:

Exception in thread "Listen" java.util.regex.PatternSyntaxException: Unmatched closing ')'
near index 0
:)
^

What should I do?

Maroun
  • 91,013
  • 29
  • 181
  • 233
FFlaser
  • 111
  • 1
  • 2
  • 8

3 Answers3

8

Don't use replaceAll(); use replace() when you want to replace literal strings:

message.replace(":)", replacement)

replaceAll() deals with regular expressions, in which ) has a special meaning, hence the error.

arshajii
  • 123,543
  • 24
  • 232
  • 276
2

You must escape ) in regexen:

message = message.replaceAll(":\\)", replacement);

This is because ) has special meaning (capture groups), so you have to "tell" regex that you just want a literal ).

tckmn
  • 55,458
  • 23
  • 108
  • 154
1

Write:

message.replaceAll(Pattern.quote(":)"), replacement);

String#replaceAll accept a regex, not a regular String. ) has a special meaning in regex, using quote will cause treating :) as the String :) and not the regex.

If you don't want to use Pattern#quote, you should escape the ) by \\. Note that escaping a regex is done by \, but in Java, \ is written as \\.

If you don't like any of the mentioned, use String#replace that doesn't accept a regex, and you're fine.

Maroun
  • 91,013
  • 29
  • 181
  • 233