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
  • 94,125
  • 30
  • 188
  • 241
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
  • 127,459
  • 24
  • 238
  • 287
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
  • 57,719
  • 27
  • 114
  • 156
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
  • 94,125
  • 30
  • 188
  • 241
  • God.... give someone opportunity to fix his mistake................ – Maroun Jan 12 '14 at 15:01
  • 2
    @DoorknobofSnow Using a `#` is a common way to separate a class name and a method/property name when referencing a method/property (typically in docs). – ajp15243 Jan 12 '14 at 15:03
  • @ajp15243 I know, but before the edit it was `message.replaceAll(Pattern#quote(":)"), replacement);` (now fixed) – tckmn Jan 12 '14 at 15:03
  • @DoorknobofSnow Ah I see, well the question went through so many edits I didn't catch that lol. – ajp15243 Jan 12 '14 at 15:04