Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between () and [] in a regex?

Tags:

regex

Let's say:

/(a|b)/ vs /[ab]/

like image 726
Cheng Avatar asked Oct 28 '09 05:10

Cheng


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.

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 escape square brackets in regex?

An escape can be either enclosing the phrase in braces, or placing a backslash before the escaped character. To pass a left bracket to the regular expression parser to evaluate as a range of characters takes 1 escape.

Are brackets special characters in regex?

The special characters are: a. ., *, [, and \ (period, asterisk, left square bracket, and backslash, respectively), which are always special, except when they appear within square brackets ([]; see 1.4 below). c. $ (dollar sign), which is special at the end of an entire RE (see 4.2 below).


1 Answers

There's not much difference in your above example (in most languages). The major difference is that the () version creates a group that can be backreferenced by \1 in the match (or, sometimes, $1). The [] version doesn't do this.

Also,

/(ab|cd)/  # matches 'ab' or 'cd'
/[abcd]/   # matches 'a', 'b', 'c' or 'd'
like image 108
Peter Avatar answered Oct 15 '22 18:10

Peter