What is the order of priority of expressions in (..|. .. .|..)
operator - left to right, right to left or something else?
In regular expressions, the ' * ', ' + ', and ' ? ' operators, as well as the braces ' { ' and ' } ', have the highest precedence, followed by concatenation, and finally by ' | '. As in arithmetic, parentheses can change how operators are grouped.
Regular expressions can be chained together using the pipe character (|). This allows for multiple search options to be acceptable in a single regex string.
The three basic operations in which regular expressions are used are: matching (Does this (entire) string match this pattern?) searching (Is this pattern found within this string?) transforming (such as replacing one or all occurrences of a pattern with another string)
Left to right, and the first alternative matched "wins", others are not checked for. This is a typical NFA regex behavior. A good description of that behavior is provided at regular-expressions.info Alternation page.
Note that RegexOptions.RightToLeft
only makes the regex engine examine the input string from right to left, the modifier does not impact how the regex engine processes the pattern itself.
Let me illustrate: if you have a (aaa|bb|a)
regex and try to find a match in bbac
using Regex.Match
, the value you will obtain is bb
because a
alternative appears after bbb
. If you use Regex.Matches
, you will get all matches, and both bb
and a
will land in your results.
Also, the fact that the regex pattern is examined from left to right makes it clear that inside a non-anchored alternative group, the order of alternatives matter. If you use a (a|aa|aaa)
regex to match against abbccaa
, the first a
alternative will be matching each a
in the string (see the regex demo). Once you add word boundaries, you can place the alternatives in any order (see one more regex demo).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With