Java - Escaping Meta-characters [ and ] in Regex

11,536

Solution 1

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.

Solution 2

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 \\.

Solution 3

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

or in the more general case

aString.replaceFirst(java.util.regex.Pattern.quote("[]"), "blah");
Share:
11,536
ZirconCode
Author by

ZirconCode

...

Updated on June 05, 2022

Comments

  • ZirconCode
    ZirconCode almost 2 years

    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