How does this code return true?
to match: ab
ab
pattern: /^a|b$/
/^a|b$/
but when I put the parentheses as follows:
pattern: /^(a|b)$/
/^(a|b)$/
he will return false.
false
The first pattern without parentheses is equivalent /(^a)|(b$)/.The reason is because the pipe operator (the "interlace operator") has the lowest priority of all regex operators: http://www.regular-expressions.info/alternation.html (Third paragraph, first header below)
/(^a)|(b$)/
/^a|b$/ , a b. , afoo, barb, a, b.
a
b
afoo
barb
/^(a|b)$/: , a b. , a, b, .
, | .
|
a b.
1 , a b.
|has a lower priority than anchors, so you say either ^a, or b$(which is true), unlike the second, which means "one character string, either a, or b" (which is incorrect).
^a
b$
In ^a|b$you are suitable for aat the beginning or bat the end.
^a|b$
In ^(a|b)$you match for aor b, which is the only character (at the beginning and at the end).
^(a|b)$