Order of regular expression operator (..|.. … ..|..)

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).

Leave a Comment