Regular Expression Confusion

How does this code return true?

to match: ab

pattern: /^a|b$/

but when I put the parentheses as follows:

pattern: /^(a|b)$/

he will return false.

+5
source share
5 answers

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)

+12
source

/^a|b$/ , a b. , afoo, barb, a, b.

/^(a|b)$/: , a b. , a, b, .

, | .

+7

a b.

1 , a b.

+4

|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).

+1
source

In ^a|b$you are suitable for aat the beginning or bat the end.

In ^(a|b)$you match for aor b, which is the only character (at the beginning and at the end).

+1
source

All Articles