Regular expressions are used for pattern matching within strings. They can be defined upon special characters, meaning symbols or metacharacters
with a reserved meaning that convey specific instructions to the regex engine. These characters are not treated as literals but have special functions
in defining patterns, among which stand out anchors and disjunctions.
- An anchor allows you to match positions in the input string rather than matching specific characters. Anchors help you identify specific
locations within the string where a pattern should start (
^
) or end ($
).
- A disjunction, also known as alternatives, represented by the vertical bar (
|
) allows you to specify multiple alternative patterns
that the regex engine will attempt to match in the input string.
Mixing anchors with alternatives in regular expressions can lead to confusion due to their precedence rules. Alternatives (|
) have a
lower precedence than anchors (^
and $
). As a result, if you don’t use non-capturing groups (?:...)
to group
the alternatives properly, the anchors might apply to the ends only rather than the entire disjunction, which could not be the initial intent.
const regex = /^a|b|c$/; // Noncompliant: '^' applies to 'a' and '$' applies to 'c'
You should group the disjunction with parentheses denoting non-capturing groups so that the anchors apply to all alternatives.
const regex = /^(?:a|b|c)$/;
Alternatively, you can distribute the anchors to each alternative of the disjunction.
const regex = /^a$|^b$|^c$/;
If the precedence of the operators is understood and the intention is to apply the anchors to only the ends, use parentheses to make it
explicit.
const regex = /(?:^a)|b|(?:c$)/;