0

Should I escape closing brackets characters (that is, ], } and )) in Perl and ECMAScript-compatible regular expressions flavors?

It looks from the answer for this question that I must not escape ] bracket but I do must to do this in case of } and ) (for PCRE). Of course, I must escape them if I want to use them inside the corresponding regular expressions sequences like (first\)|second) or [ab\]] but what about other cases?

For example, should I escape them in the following case?

Regular expression -- str\[]

Input string -- str[]

Community
  • 1
  • 1
FrozenHeart
  • 19,844
  • 33
  • 126
  • 242
  • Just my opinion, but if the linked question is unclear, it might be better to comment on it asking for clarification and then edit it when you have your answer. It gets A LOT of views (currently at 125,769) and is used to close a lot of duplicates, so it should really be as clear as possible. Having separate questions just to clarify another question seems like information scattering; I think consolidation would be better. – ThisSuitIsBlackNot Nov 30 '15 at 17:17
  • (Note that the author of the accepted answer is currently active and responded to a comment seeking clarification just 10 days ago.) – ThisSuitIsBlackNot Nov 30 '15 at 17:18
  • For Perl (not to be confused with PCRE), the rules for escaping curly braces are changing. Before Perl 5.22.0, you didn't even have to escape `{`: `perl -e'/foo{/'`. 5.22.0 introduced a deprecation warning for this and mentions that "a future version of Perl (tentatively v5.26) will consider this to be a syntax error. If the pattern delimiters are also braces, any matching right brace (`}`) should also be escaped to avoid confusing the parser, for example, `qr{abc\{def\}ghi}`". – ThisSuitIsBlackNot Nov 30 '15 at 18:15
  • Re "It looks from the answer for this question that I must not escape `]` bracket", That's not true. You may escape `]`. You may escape any non-word characters, at least in the ASCII range. – ikegami Nov 30 '15 at 18:21

2 Answers2

0

PCRE is pretty easy to test with pgrep:

echo 'str[]' | grep -P 'str\[]'

I tested JS in my Chrome browser, I pressed F12 to get to the Console and tried

"str[]".match(/str\[]/)
choroba
  • 231,213
  • 25
  • 204
  • 289
0

Perl:

$ perl -wE'say "a]b" =~ /a]b/'
1

$ perl -wE'say "a]b" =~ /a\]b/'
1

$ perl -wE'say "a}b" =~ /a}b/'
1

$ perl -wE'say "a}b" =~ /a\}b/'
1

$ perl -wE'say "a)b" =~ /a)b/'
Unmatched ) in regex; marked by <-- HERE in m/a) <-- HERE / at -e line 1.

$ perl -wE'say "a)b" =~ /a\)b/'
1

So ] and } need not be escaped, but may be escaped. ) must be escaped.

Note that certain { that didn't need escaping before now need escaping in Perl. The reason for that change doesn't apply to closing braces, though.

ikegami
  • 367,544
  • 15
  • 269
  • 518