简体   繁体   English

为什么 Regex.Replace 没有按预期工作?

[英]Why is Regex.Replace not working as expected?

Given the strings "Hello" + "{l}:1" , the following method should only replace the first occurrence of the character l in the left string (any number of characters can be matched here though).给定字符串"Hello" + "{l}:1" ,下面的方法应该只替换左侧字符串中第一次出现的字符l (尽管这里可以匹配任意数量的字符)。

private static string SubtractString(string left, string right)
{
    bool TryReplace(string pattern, out string output)
    {
        var match = Regex.Match(right, pattern);
        if (match.Success)
        {
            output = Regex.Replace(left, $@"{match.Groups[1].Value}{{{match.Groups[2].Value}}}", string.Empty);
            return true;
        }

        output = null;
        return false;
    }
    
    if (TryReplace(@"{(.+)}:([1-9]+|\*{1})", out var result))
        return result;
    
    return TryReplace(@"(.{1}):([1-9]+|\*{1})", out result) ? result : left.Replace(right, string.Empty);
}

The expected output should be Helo but I instead get Heo .预期的 output 应该是Helo但我却得到了Heo The pattern being generated ( $@"{match.Groups[1].Value}{{{match.Groups[2].Value}}}" ) evaluates to l{1} which should only match once.正在生成的模式( $@"{match.Groups[1].Value}{{{match.Groups[2].Value}}}" )计算结果为l{1} ,它应该只匹配一次。

Using https://regexr.com/6eapt I can only find this behaviour with the global flag enabled which I haven't set in my code.使用https://regexr.com/6eapt我只能在启用了我没有在我的代码中设置的全局标志的情况下找到这种行为。

Any help would be much appreciated, Thanks.任何帮助将不胜感激,谢谢。

I think this is caused by a confusion created from regexr allowing you to play with JavaScript expressions;我认为这是由 regexr 造成的混乱造成的,它允许您使用 JavaScript 表达式; they're subtly different to .net ones.它们与 .net 略有不同。 By default a JavaScript expression only replaces the first match it comes across whereas Regex.Replace in .net will replace all matches it comes across.默认情况下,JavaScript 表达式仅替换它遇到的第一个匹配项,而 .net 中的 Regex.Replace 将替换它遇到的所有匹配项。 Your string of "Hello" and resulting pattern of "l{1}" will find two matches您的“Hello”字符串和"l{1}"的结果模式将找到两个匹配项

If you want "just replace the first match" you'll need to switch to using a non static method如果您想“只替换第一个匹配项”,您需要切换到使用非 static 方法

        output = new Regex($@"{match.Groups[1].Value}{{{match.Groups[2].Value}}}").Replace(left, string.Empty, 1);
        
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM