3

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.

Over Killer
  • 507
  • 9
  • 24

2 Answers2

4

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

zx81
  • 41,100
  • 9
  • 89
  • 105
  • If i use ```\[``` or ```\]```, i'm getting warning about unregonized escape literal. – Over Killer Jul 25 '14 at 12:39
  • @user3811473 It does in some engines, Ruby for instance. This is why I gave all these examples about the different engines. – zx81 Jul 25 '14 at 12:52
  • @zx81: agreed, I'll leave my answer for extra info but voted up your answer because its more complete :) – user3811473 Jul 25 '14 at 12:57
  • @GermánDiago Saw your edit attemps. Good idea to explain string options. Added a section for this, and took the C++11 from your suggestions after minor edits—thank you. :) – zx81 Jul 25 '14 at 20:27
1

\[ 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