0

I am trying to use RegEx to replace a string, but nothing is being replaced. I'm not sure what I'm doing wrong.

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 is of type string, and contains the html page content of the Render method (write before we send it to the browser). The htmlPageContent string definitely contains "DefaultStyle.css?x=839ua9". I can see it when I do Quick Watch in visual studio, and when I view Page Source.

Why is RegEx not replacing the string?

Pavel
  • 704
  • 11
  • 25

2 Answers2

2

You have to use \? and \. instead of ? and . in your Regex. Please check below code.

CODE:

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);
    }
}

Output:

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

You can check the output in DotNetFiddle.

csharpbd
  • 3,786
  • 4
  • 23
  • 32
1

You need to escape your special characters using \.

System.Text.RegularExpressions.Regex regEx = null;

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

You need to explicitly escape the ? which means 0 or more of the previous character.

As for the . if you do not escape it, you will match any characters. It would be more precise to escape it as well to make sure you don't match something like

DefaultStyle-css?x=839ua9
Gilles
  • 5,269
  • 4
  • 34
  • 66