Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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";

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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, "");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading