【问题标题】:C# Regex Replace using match valueC# 正则表达式替换使用匹配值
【发布时间】:2012-09-19 10:23:40
【问题描述】:

我正在尝试用 C# 编写一个函数,用自定义字符串替换所有出现的正则表达式模式。我需要使用匹配字符串来生成替换字符串,所以我试图循环匹配而不是使用 Regex.Replace()。当我调试我的代码时,正则表达式模式匹配我的 html 字符串的一部分并进入 foreach 循环,但是 string.Replace 函数不会替换匹配项。有谁知道是什么原因导致这种情况发生?

我的函数的简化版:-

public static string GetHTML() {
    string html = @"
        <h1>This is a Title</h1>
        @Html.Partial(""MyPartialView"")
    ";

    Regex ItemRegex = new Regex(@"@Html.Partial\(""[a-zA-Z]+""\)", RegexOptions.Compiled);
    foreach (Match ItemMatch in ItemRegex.Matches(html))
    {
        html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>");
    }

    return html;
}

【问题讨论】:

  • string 对象是不可变的,以进一步解释@sethflowers 的答案。
  • 您为什么使用Compiled 选项?只有当您有明确的需要时,您才应该使用它。它提供的性能提升并不是那么好,而且它不是免费的。 ref

标签: c# regex


【解决方案1】:

string.Replace 返回一个字符串值。您需要将其分配给您的 html 变量。请注意,它还会替换所有出现的匹配值,这意味着您可能不需要循环。

html = html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>");

返回一个新字符串,其中所有出现的指定字符串都在 当前实例被另一个指定的字符串替换。

【讨论】:

  • 谢谢,当我意识到时自己添加了答案,但你打败了我。
【解决方案2】:

你没有重新分配给 html

所以:

html = html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>"); 

【讨论】:

    【解决方案3】:

    正如其他答案所述,您没有分配结果值。

    我要补充一点,您的 foreach 循环没有多大意义,您可以使用内联替换:

    Regex ItemRegex = new Regex(@"@Html.Partial\(""[a-zA-Z]+""\)", RegexOptions.Compiled);
    html = ItemRegex.Replace(html, "<h2>My Partial View</h2>");
    

    【讨论】:

      【解决方案4】:

      这个怎么样?这样你就使用匹配中的值来替换?

      然而,最大的问题是您没有将替换结果重新分配给 html 变量。

      using System;
      using System.Text.RegularExpressions;
      
      namespace ConsoleApplication2
      {
          class Program
          {
              static void Main(string[] args)
              {
                  var html = @"
                                  <h1>This is a Title</h1>
                                  @Html.Partial(""MyPartialView"")
                              ";
      
                  var itemRegex = new Regex(@"@Html.Partial\(""([a-zA-Z]+)""\)", RegexOptions.Compiled);
                  html = itemRegex.Replace(html, "<h2>$1</h2>");
      
                  Console.WriteLine(html);
                  Console.ReadKey();
              }
          }
      }
      

      【讨论】:

        【解决方案5】:

        感觉很傻。该字符串是不可变的,所以我需要重新创建它。

        html = html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>");
        

        【讨论】:

        • 您可能会注意到发布之间的时间间隔很小。我正在写我的anwser,而另一个被发布,所以我没有看到它们。很抱歉我没有接受你的回答我可能没有很好地提出我的问题。
        猜你喜欢
        • 2016-05-23
        • 2012-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-30
        • 1970-01-01
        • 2013-12-06
        • 2021-04-10
        相关资源
        最近更新 更多