正则表达式运算符(.. | .. ... .. | ..)的顺序 [英] Order of regular expression operator (..|.. ... ..|..)
问题描述
(.. |。.. ....)
运算符中表达式的优先级顺序是从左到右,从右到左还是其他?
What is the order of priority of expressions in (..|. .. .|..)
operator - left to right, right to left or something else?
推荐答案
从左到右,第一个与 wins匹配的单词,不检查其他单词。这是典型的NFA正则表达式行为。 regular-expressions.info Alternation 页面。
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.
请注意, RegexOptions.RightToLeft
仅使regex引擎有效从右到左检查输入字符串,修饰符不会影响正则表达式引擎如何处理模式本身。
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.
让我说明一下:如果您有(aaa | bb | a)
正则表达式,并尝试使用 Regex.Match在
,您将获得的值为 bbac
中找到匹配项 bb
,因为 a
替代出现在之后bbb
。如果使用 Regex.Matches
,则将获得所有匹配项,并且同时包含 bb
和 a
将会出现在您的结果中。
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.
此外,从左到右检查正则表达式的事实也清楚地表明了 inside一个非锚定的替代组,替代的顺序很重要。如果使用(a | aa | aaa)
正则表达式与 abbccaa
匹配,则第一个 a
替代将匹配字符串中的每个 a
(请参见 regex演示)。添加单词边界后,您可以按任何顺序放置替代项(请参见一个正则表达式演示)。
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).
这篇关于正则表达式运算符(.. | .. ... .. | ..)的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!