Regular Expressions -Operator Precedence
Regular expressions are evaluated from left to right and follow an order of precedence, which is very similar to arithmetic expressions.
Operations with the same precedence are performed from left to right, while operations with different precedence are performed from high to low. The following table illustrates the precedence order of various regular expression operators from highest to lowest:
| Operator | Description |
|---|---|
| \ | Escape character |
| (), (?:), (?=), [] | Parentheses and square brackets |
| *, +, ?, {n}, {n,}, {n,m} | Quantifier |
| ^, $, \ any metacharacter, any character | Anchors and sequences (i.e., position and order) |
| | | Alternation, "or" operation Characters have 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 in order of precedence from highest to lowest:
Escape symbol:
\It is an escape symbol used to escape other special characters. It has the highest precedence.Example:
\d、\.etc., where\dmatches a digit,\.matches a dot.Parentheses:Parentheses
()are used to create subexpressions and have higher precedence than other operators.Example:
(abc)+Matches "abc" one or more times.Quantifiers:Quantifiers specify the number of times the preceding element can be repeated.
Example:
a*Matches zero or more "a".Character classes:Character classes use square brackets
[]to match any character within the brackets.Example:
[aeiou]Matches any one of the vowel letters.Assertions:Assertions are elements used to check conditions at specific positions in a string.
Example:
^represents the beginning 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 and is used to select one among multiple patterns.Example:
cat|dogMatches "cat" or "dog".
Next, let's look at the precedence explanation of the following regular expressions:
\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".