Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

c# - Order of regular expression operator (..|.. ... ..|..)

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...