Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression pipe confusion

Tags:

regex

How come this code returns true?

string to match: ab

pattern: /^a|b$/

but when I put parentheses like this:

pattern: /^(a|b)$/

it will then return false.

like image 925
Rei Avatar asked Jun 08 '11 13:06

Rei


5 Answers

The first pattern without the parenthesis is equivalent to /(^a)|(b$)/.
The reason is, that the pipe operator ("alternation operator") has the lowest precedence of all regex operators: http://www.regular-expressions.info/alternation.html (Third paragraph below the first heading)

like image 86
Daniel Hilgarth Avatar answered Nov 19 '22 02:11

Daniel Hilgarth


/^a|b$/ matches a string which begins with an a OR ends with a b. So it matches afoo, barb, a, b.

/^(a|b)$/ : Matches a string which begins and ends with an a or b. So it matches either an a or b and nothing else.

This happens because alteration | has very low precedence among regex operators.

Related discussion

like image 30
codaddict Avatar answered Nov 19 '22 03:11

codaddict


The first means begin by an a or end with a b.

The second means 1 character, an a or a b.

like image 34
AProgrammer Avatar answered Nov 19 '22 02:11

AProgrammer


In ^a|b$ you are matching for an a at the beginning or a b at the end.

In ^(a|b)$ you are matching for an a or a b being the only character (at beginning and end).

like image 27
Cobra_Fast Avatar answered Nov 19 '22 03:11

Cobra_Fast


| has lower priority than the anchors, so you're saying either ^a or b$ (which is true) as opposed to the 2nd one which means "a single character string, either a or b" (which is false).

like image 1
Blindy Avatar answered Nov 19 '22 02:11

Blindy