In regular expressions, anchors (^
, $
, \A
, \Z
and \z
) have higher precedence than
the |
operator. So in a regular expression like ^alt1|alt2|alt3$
, alt1
would be anchored to the beginning,
alt3
to the end and alt2
wouldn’t be anchored at all. Usually the intended behavior is that all alternatives are anchored at
both ends. To achieve this, a non-capturing group should be used around the alternatives.
In cases where it is intended that the anchors only apply to one alternative each, adding (non-capturing) groups around the anchors and the parts
that they apply to will make it explicit which parts are anchored and avoid readers misunderstanding the precedence or changing it because they
mistakenly assume the precedence was not intended.
Noncompliant code example
^a|b|c$
Compliant solution
^(?:a|b|c)$
or
^a$|^b$|^c$
or, if you do want the anchors to only apply to a
and c
respectively:
(?:^a)|b|(?:c$)