【问题标题】:C# Regex replace is not working [duplicate]C#正则表达式替换不起作用[重复]
【发布时间】:2017-04-28 16:51:01
【问题描述】:

我正在尝试使用 RegEx 替换字符串,但没有任何内容被替换。我不确定我做错了什么。

System.Text.RegularExpressions.Regex regEx = null;

regEx = new System.Text.RegularExpressions.Regex("DefaultStyle.css?x=839ua9");
pageContent = regEx.Replace(htmlPageContent, "DefaultStyleSnap.css?x=742zh2");

htmlPageContent 是 string 类型,包含 Render 方法的 html 页面内容(在发送到浏览器之前写入)。 htmlPageContent 字符串肯定包含“DefaultStyle.css?x=839ua9”。当我在 Visual Studio 中进行快速观看以及查看页面源时,我可以看到它。

为什么 RegEx 没有替换字符串?

【问题讨论】:

  • ? 是一个特殊字符。你不应该使用正则表达式。
  • 如果您需要将文字传递给正则表达式模式,请使用 Regex.Escape("DefaultStyle.css?x=839ua9")
  • 您正在执行直接替换。为什么要使用正则表达式?我建议只使用内置字符串Replace 函数。

标签: c# regex


【解决方案1】:

您必须在Regex 中使用\?\. 而不是?.。请检查以下代码。

代码:

using System;

public class Program
{
    public static void Main()
    {
        string htmlPageContent = "Some HTML <br> DefaultStyle.css?x=839ua9";
        string pageContent = "";

        System.Text.RegularExpressions.Regex regEx = null;

        //regEx = new System.Text.RegularExpressions.Regex("DefaultStyle.css?x=839ua9");
        regEx = new System.Text.RegularExpressions.Regex(@"DefaultStyle\.css\?x=839ua9");
        pageContent = regEx.Replace(htmlPageContent, "DefaultStyleSnap.css?x=742zh2");

        Console.WriteLine(pageContent);
    }
}

输出:

Some HTML <br> DefaultStyleSnap.css?x=742zh2

您可以查看DotNetFiddle中的输出。

【讨论】:

    【解决方案2】:

    您需要使用 \ 转义您的特殊字符。

    System.Text.RegularExpressions.Regex regEx = null;
    
    regEx = new System.Text.RegularExpressions.Regex("DefaultStyle\.css\?x=839ua9");
    pageContent = regEx.Replace(htmlPageContent, "DefaultStyleSnap.css?x=742zh2");
    

    您需要明确转义 ?,这意味着前一个字符的 0 个或多个。

    至于.,如果不转义,则匹配任意字符。转义它会更精确,以确保你不匹配像

    这样的东西
    DefaultStyle-css?x=839ua9
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-08
      • 2017-05-13
      • 2023-03-23
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多