Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Special Characters in Regex Brackets

Let's say I want to match one of the following characters: a, b, c, or + (in JavaScript). Do I need to escape the +? Is it /[abc+]/ or /[abc\+]/? Both work in my limited selection of test browsers. Which is (more) correct?

like image 448
Casey Chu Avatar asked Jul 09 '10 07:07

Casey Chu


People also ask

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

What do the [] brackets mean in regular expressions?

By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex.

How do you write brackets in regex?

[[\]] will match either bracket. In some regex dialects (e.g. grep) you can omit the backslash before the ] if you place it immediately after the [ (because an empty character class would never be useful): [][] .


2 Answers

Regex reference

Under character classes:

Any character except ^-]\ add that character to the possible matches for the character class.

In other words, you don't have to escape the +.

like image 69
Aistina Avatar answered Sep 18 '22 17:09

Aistina


No need to escape the + in character class [xxx]:

/[abc+]/
like image 38
Sarfraz Avatar answered Sep 20 '22 17:09

Sarfraz