Regular Expressions - Operator Precedence
Regular expressions are evaluated from left to right and follow a precedence order, similar to arithmetic expressions.
Operators of the same precedence are evaluated from left to right, while operators of different precedence are evaluated from higher to lower. The table below lists the precedence order 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". |