正则表达式运算符的顺序 (..|.. ... ..|..) [英] Order of regular expression operator (..|.. ... ..|..)

查看:40
本文介绍了正则表达式运算符的顺序 (..|.. ... ..|..)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(..|. .. .|..) 运算符中表达式的优先级顺序是什么 - 从左到右、从右到左或其他什么?

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 仅使正则表达式引擎从右到左检查输入字符串,修饰符不会影响正则表达式引擎本身处理模式的方式.

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.Matchbbac 中找到匹配项code>,您将获得的值是 bb 因为 a 替代出现在 bbb 之后.如果您使用 Regex.Matches,您将获得所有匹配项,并且 bba 都将出现在您的结果中.

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.

此外,从左到右检查正则表达式模式这一事实清楚地表明在非锚定替代组中,替代的顺序很重要.如果您使用 (a|aa|aaa) 正则表达式来匹配 abbccaa,第一个 a 替代将匹配每个 a 在字符串中(参见 正则表达式演示).添加单词边界后,您可以按任何顺序放置替代项(请参阅 又一个正则表达式演示).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆