Why does this pattern fail to compile :
Pattern.compile("(?x)[ ]\\b");
Error
ERROR java.util.regex.PatternSyntaxException:
Illegal/unsupported escape sequence near index 8
(?x)[ ]\b
^
at java_util_regex_Pattern$compile.call (Unknown Source)
While the following equivalent ones work?
Pattern.compile("(?x)\\ \\b");
Pattern.compile("[ ]\\b");
Pattern.compile(" \\b");
Is this a bug in the Java regex compiler, or am I missing something? I like to use [ ]
in verbose regex instead of backslash-backslash-space because it saves some visual noise. But apparently they are not the same!
PS: this issue is not about backslashes. It's about escaping spaces in a verbose regex using a character class containing a single space [ ]
instead of using a backslash.
Somehow the combination of verbose regex (?x)
and a character class containing a single space [ ]
throws the compiler off and makes it not recognize the word boundary escape \b
Tested with Java up to 1.8.0_151
x
flag (enabled by the OP's(?x)
) causes whitespace and comments to be ignored; so(?x)a b
is equivalent toab
, whereas(?x)a\ b
is equivalent toa b
. As Socowi explains in his/her answer, the problem is that the OP expected(?x)a[ ]b
to be equivalent toa[ ]b
(i.e. toa b
), when in fact it's equivalent toa[]b
(which is invalid).[ ]
is a valid way to escape spaces in verbose regex, see for example Perl:echo 'a b' | perl -lne 'print if /a[ ]b/x'
or libpcre:echo 'a b' | pcregrep '(?x)a[ ]b'