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