What is the order of priority of expressions in (..|. .. .|..)
operator - left to right, right to left or something else?

- 1,485
- 2
- 22
- 35
1 Answers
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).

- 607,720
- 39
- 448
- 563
-
I think there are regex engines which always take the longest match, instead of the first here. – Joey Feb 24 '16 at 15:54
-
2POSIX-compliant regex engines require the longest match. Also, Perl6 `/ pattern1 | pattern2 /` also matches the longest alternative (there is a `||` operator that works as a simple `|` in most other flavors to yield the first found alternative). – Wiktor Stribiżew Feb 24 '16 at 15:55
-
In Python 3.8.2 (CPython) it seems to be left to right too, not the longest one. Example: `re.sub(r"3rd (col|column)", '_', '3rd column')` returns `'_umn'` – fersarr Mar 03 '21 at 13:24