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.
Asked
Active
Viewed 188 times
3

Over Killer
- 507
- 9
- 24
-
I'm using C++11 regular expressions inside string. – Over Killer Jul 25 '14 at 12:37
-
2Note that you don't need to escape everything twice if you use a raw string literal: `R"([\[\]])"` – chris Jul 25 '14 at 13:08
2 Answers
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 PythonR"(\])"
orR"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

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 ]
:)

user3811473
- 92
- 4
-
Now I'm getting this error: ```regex_error(error_brack): The expression contained mismached [ and ]```. Regexp: ```\\[]``` (it is inside of string) – Over Killer Jul 25 '14 at 12:47
-
-
Not really a concrete text. I want know that a form won't contain any "non-name" chars. – Over Killer Jul 25 '14 at 12:55