为了账号安全,请及时绑定邮箱和手机立即绑定

为什么选择的顺序在正则表达式中很重要?

为什么选择的顺序在正则表达式中很重要?

当年话下 2019-12-06 15:13:13
码using System;using System.Text.RegularExpressions;namespace RegexNoMatch {    class Program {        static void Main () {            string input = "a foobar& b";            string regex1 = "(foobar|foo)&?";            string regex2 = "(foo|foobar)&?";            string replace = "$1";            Console.WriteLine(Regex.Replace(input, regex1, replace));            Console.WriteLine(Regex.Replace(input, regex2, replace));            Console.ReadKey();        }    }}预期产量a foobar ba foobar b实际产量a foobar ba foobar& b题当正则表达式模式中的“ foo”和“ foobar”的顺序更改时,为什么替换不起作用?如何解决这个问题?
查看完整描述

2 回答

?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

正则表达式引擎尝试按指定的顺序匹配替代项。因此,当模式正确时,(foo|foobar)&?它将foo立即匹配并继续尝试查找匹配项。输入字符串的下一位bar& b不能匹配。


换句话说,因为foo是的一部分foobar,所以(foo|foobar)永远不会匹配foobar,因为它将始终foo首先匹配。


实际上,有时候这可能是一个非常有用的技巧。该模式(o|a|(\w))将允许您捕获\w和a或以其他方式捕获o:


Regex.Replace("a foobar& b", "(o|a|(\\w))", "$2") // fbr& b


查看完整回答
反对 回复 2019-12-06
  • 2 回答
  • 0 关注
  • 627 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信