Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match "[" and "]" in regexp?

How to match "[" and "]" in regular expression? This one does not work: [\\[\\]] I thought that \\ enables use of special character. I want to match them inside a class.

like image 369
Over Killer Avatar asked Jan 18 '26 22:01

Over Killer


2 Answers

It depends on your engine, and on whether you want to match a specific bracket (opening vs. closing), or to match a class of brackets.

  • \[ matches opening bracket
  • \] matches closing bracket
  • [][] matches one char that is either an opening or closing bracket (.NET, Perl, PCRE, Python)
  • []\[] same as above (Java and the 4 engines above)
  • [[\]] same as above (JavaScript and the 4 engines above)
  • [\]\[] same as above (Ruby, all engines)

Avoiding Backslash Soup

A handful of languages, such as Java, requires you to escape backslashes in the regex string, leading to \\[ and other unsightly variations. Fortunately, most languages give you ways to avoid escaping backslashes.

  • "\[" can be used as is in JavaScript, PHP, Perl, Ruby, VB.NET, VBScript
  • @"\[" (verbatim string) in C#
  • r"\[" (raw string) in Python
  • R"(\])" or R"foo(\])foo" in C++11 (raw string literal). A raw string lives between parentheses, which can be surrounded by an optional delimiter (foo in the second version).

Reference

Interesting Character Classes

like image 87
zx81 Avatar answered Jan 20 '26 10:01

zx81


\[ and ] should work. In some languages you may have to double escape. (i.e. \\[ and ]).

Note: You don't need to escape ] :)

DEMO: http://regex101.com/r/vP4mQ9/1

like image 20
user3811473 Avatar answered Jan 20 '26 10:01

user3811473