Regular Expression - Operator Precedence
Regular expressions are evaluated from left to right following a precedence order, much like arithmetic expressions.
Operations with the same precedence are evaluated left to right, while operations with different precedence are evaluated high to low. The table below explains the precedence order of various regular expression operators from highest to lowest:
| operator | Description |
|---|---|
| \ | Escape Character |
| (), (?:), (?=), [] | Parentheses and Square Brackets |
| *, +, ?, {n}, {n,}, {n,m} | Qualifier |
| ^, $, \ any metacharacter, any character | Anchors and sequences (i.e., position and order) |
| | | Alternation, the "or" operation |
| The character has higher precedence than the alternation operator, so "m|food" matches "m" or "food". To match "mood" or "food", use parentheses to create a subexpression, resulting in "(m|f)ood". |
The following are some common regular expression operators listed from highest to lowest precedence:
-
Escape symbol:
\is the escape symbol used to escape other special characters. It has the highest precedence.Example:
\d,\.and so on, where\dmatches digits,\.matches a dot. -
Parentheses: Parentheses
()Used to create subexpressions, with higher precedence than other operators.Example:
(abc)+Matches "abc" one or more times. -
Quantifiers: Quantifiers specify how many times the preceding element can repeat.
Example:
a*Matches zero or more "a". -
Character classes: Character classes use square brackets
[]to represent a set used to match any character inside the brackets.Example:
[aeiou]Matches any vowel letter. -
Assertions: Assertions are elements used to check conditions at specific positions in a string.
Example:
^represents the start of a line,$represents the end of a line. -
Concatenation: Concatenation represents the simple joining of characters when no other operator is present.
Example:
abcMatches "abc". -
Pipe: The pipe symbol
|represents an "or" relationship, used to choose among multiple patterns.Example:
cat|dogMatches "cat" or "dog".
Next, let us look at the following explanations of regular expression precedence:
\d{2,3}|[a-z]+(abc)*
\d{2,3}Matches two to three digits.|represents "or".[a-z]+Matches one or more lowercase letters.(abc)*Matches zero or more "abc".