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.
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"(\])" 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
\[ 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With