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
.
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
.
/^a|b$/
matches a string which begins with ana
OR ends with ab
. So it matchesafoo
,barb
,a
,b
./^(a|b)$/
: Matches a string which begins and ends with ana
orb
. So it matches either ana
orb
and nothing else.This happens because alteration
|
has very low precedence among regex operators.Related discussion
|
has lower priority than the anchors, so you're saying either^a
orb$
(which is true) as opposed to the 2nd one which means "a single character string, eithera
orb
" (which is false).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)
In
^a|b$
you are matching for ana
at the beginning or ab
at the end.In
^(a|b)$
you are matching for ana
or ab
being the only character (at beginning and end).The first means begin by an
a
or end with ab
.The second means 1 character, an
a
or ab
.