[regex] What's the regular expression that matches a square bracket?

I want a regex that matches a square bracket [. I haven't found one yet. I think I tried all possibilities, but haven't found the right one. What is a valid regex for this?

This question is related to regex

The answer is


How about using backslash \ in front of the square bracket. Normally square brackets match a character class.


does it work with an antislash before the [ ?

\[ or \\[ ?


In general, when you need a character that is "special" in regexes, just prefix it with a \. So a literal [ would be \[.


Try using \\[, or simply \[.


If you want to remove the [ or the ], use the expression: "\\[|\\]".

The two backslashes escape the square bracket and the pipe is an "or".


If you're looking to find both variations of the square brackets at the same time, you can use the following pattern which defines a range of either the [ sign or the ] sign: /[\[\]]/


If you want to match an expression starting with [ and ending with ], use \[[^\]]*\].


Are you escaping it with \?

/\[/

Here's a helpful resource to get started with Regular Expressions:

Regular-Expressions.info