有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

c#为什么在正则表达式中替代项的顺序很重要?

代码

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 b
a foobar b

实际产出

a foobar b
a foobar& b

问题

当regex模式中“foo”和“foobar”的顺序发生变化时,为什么替换不起作用?如何解决这个问题


共 (0) 个答案