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

2
  • 2
    How about using the Pattern.quote method? (As shown in this question) Commented Oct 26, 2011 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. Commented Oct 26, 2011 at 15:16

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked. I tried \Q and \E but not with double backslashes. Thanks. Accepting as answer in 3min
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 \\.

1 Comment

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.
2
aString.replaceFirst("\\[\\]", "blah");

or in the more general case

aString.replaceFirst(java.util.regex.Pattern.quote("[]"), "blah");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.