3

I am attempting to replace the first occurrence of the string "[]" in another string:

aString.replaceFirst("[]", "blah");

I get the error: java.util.regex.PatternSyntaxException: Unclosed character class near index 1 []

[ and ] are obviously metacharacters, however when I try to escape them with a \ eclipse complains that it is not a valid escape sequence.

I've looked but couldn't find, what am I missing?

Thank You

ZirconCode
  • 805
  • 2
  • 10
  • 24
  • 2
    How about using the [Pattern.quote](http://download.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)) method? (As shown in [this question](http://stackoverflow.com/questions/60160/how-to-escape-text-for-regular-expression-in-java)) – Brad Christie Oct 26 '11 at 15:08
  • That worked, thank you very much. Pattern.quote() produces a string which eclipse would not accept (using \Q and \E), but it is a valid workaround. Thanks. – ZirconCode Oct 26 '11 at 15:16

3 Answers3

6

Regex patterns use \ as escape character, but so does Java. So to get a single escape (\) in a regex pattern you should write: \\. To escape an escape inside a regex, double the pattern: \\\\.

Of course that's extremely tedious, made all the worse because regexes have a ton of escape sequences like that. Which is why Java regexes also support “quoting” litteral parts of the pattern and this allows you to write your pattern as: \\Q[]\\E.

EDIT: As the other answer hints at: java.util.regex.Pattern.quote() performs this wrapping between \\Q and \\E.

user268396
  • 11,576
  • 2
  • 31
  • 26
4

Try \\[ and \\]. You need to double escape, because \ is also an escape character for strings (as is \" when you want to have double-quotes in your text). Therefore to get a \ in your string you have to use \\.

pushy
  • 9,535
  • 5
  • 26
  • 45
  • That didn't throw an error, however it did not actually replace [] and work as intended. I don't know why it failed. Using Pattern.quote() worked however. – ZirconCode Oct 26 '11 at 15:15
2
aString.replaceFirst("\\[\\]", "blah");

or in the more general case

aString.replaceFirst(java.util.regex.Pattern.quote("[]"), "blah");
ratchet freak
  • 47,288
  • 5
  • 68
  • 106