Regex Replace exact matching ( include special character )

I have a string;

string input = "John + Daniels";

I want to replace the word " + Daniels" with a space.

like this: input = "John";

https://dotnetfiddle.net/bakGp9

using System;
using System.Text;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
string input = "John + Daniels";
        
string withSpecialCharacter = string.Concat("\b" + " + Daniels" + "\b");
    
StringBuilder tempString = new StringBuilder();
tempString.AppendFormat(@"{0}", withSpecialCharacter);
string finalString = tempString.ToString();
        

string result = Regex.Replace(input, finalString, "");
        

Console.WriteLine(result);
    }
}

but Replace doesn’t work.
output = "John + Daniels";

>Solution :

Pass your verbatim input to Regex.Escape in order to appropriately escape it for use in a pattern. Make sure to use verbatim string literals (@"...") for the \b escape sequence:

string pattern = @"\b" + Regex.Escape(" + Daniels") + @"\b";
// ...
string result = Regex.Replace(input, pattern, "");

Leave a Reply