Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么在正则表达式中替代项的顺序很重要?_C#_.net_Regex - Fatal编程技术网

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

C# 为什么在正则表达式中替代项的顺序很重要?,c#,.net,regex,C#,.net,Regex,代码 using System; using System.Text.RegularExpressions; namespace RegexNoMatch { class Program { static void Main () { string input = "a foobar& b"; string regex1 = "(foobar|foo)&?"; string rege

代码

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
实际产出

a foobar b
a foobar b
a foobar b
a foobar& b
问题


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

正则表达式引擎尝试按照指定的顺序匹配替代项。因此,当模式为
(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

为什么正则表达式不贪婪?我认为它应该匹配它所能匹配的最长字符串。@Athari greediness适用于量词,而不是交替。有没有办法强制对交替进行greediness,或者我必须按相反的字母顺序对交替进行排序?@Athari字母顺序没有区别。应首先按最广泛的模式对替换进行排序,例如,
foobar
foo
更广泛,因为匹配
foo
的任何字符串也将匹配
foobar
(当然
foo(bar)?
在这里更合理)。除非你试图使用我更新的答案中描述的技巧。在我的实际情况中,这个列表很长,所以让正则表达式更复杂是不值得的。我想解决了我的问题,因为我需要匹配不同的单词。