gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:41:56 25 4
gpt4 key购买 nike

代码

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

问题

为什么当正则表达式模式中“foo”和“foobar”的顺序改变时替换不起作用?如何解决这个问题?

最佳答案

正则表达式引擎尝试按照指定的顺序匹配备选方案。因此,当模式为 (foo|foobar)&? 时,它会立即匹配 foo 并继续尝试查找匹配项。输入字符串的下一位是无法匹配的bar& b

换句话说,因为 foofoobar 的一部分,所以 (foo|foobar) 永远不会匹配 foob​​ar,因为它总是首先匹配 foo

有时候,这实际上是一个非常有用的技巧。模式 (o|a|(\w)) 将允许您捕获 \wao 不同的是:

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

关于c# - 为什么替代项的顺序在正则表达式中很重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18017661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com