Regular Expressions - Operator Precedence
Regular expressions are evaluated from left to right and follow precedence rules, similar to arithmetic expressions.
Operators of the same precedence are evaluated from left to right, while those of different precedence are evaluated from higher to lower. The table below lists the precedence of various regular expression operators from highest to lowest:
Operator | Description |
---|---|
\ | Escape character |
(), (?:), (?=), [] | Parentheses and square brackets |
*, +, ?, {n}, {n,}, {n,m} | Quantifiers |
^, $, \any meta character, any character | Anchors and sequences (i.e., position and order) |
| | Alternation, "or" operation <br>Characters have higher precedence than the alternation operator, making "m|food" match "m" or "food". To match "mood" or "food", use parentheses to create a subexpression, resulting in "(m|f)ood". |