String Replace For a specific substring only

I have two lines

string One="This is StackOverFlow, Thisis StackOverFlow, Thisis";

string Two="Hello HelloHello Hello This is StackOverFlow!"

      

I want to replace every single This with Hello all B for row One,

And every single Hello to Hello Everyone In for row Two

I am trying it with this way:

One.Replace("This is","Hello Everyone In");

Output: Hello Everyone In StackOverFlow, Thisis StackOverFlow, Thisis

      


Two.Replace("Hello", "Hello Everyone In")

Output: Hello Everyone In Hello Everyone InHello Everyone In Hello Everyone In This is StackOverFlow!

      

As you can see, I want to replace Hello with this string, but it will also replace HelloHello, and HelloHello has a different meaning for my program, so it should be in its original form.

On line One Thisis is treated as a string with a different line, but why on Line Two is it treating HelloHello as Hello repetition
can anyone work it out?

Sorry for my bad english

+3


source to share


1 answer


You have to make sure you check the exact words. \b

ensures that you are only looking at exact matches, not at matches that are part of different words. As the docs explain it:

The match must occur at the border between \ w (alphanumeric) and \ W (nonalphanumeric).

Something like this should work for you:

string yourInputString = "Hello HelloHello Hello This is StackOverFlow!";
string wordYouWantToReplace = @"\bHello\b";
string replaceWordTo = "Hello Everyone In";
string result = Regex.Replace(yourInputString, wordYouWantToReplace, replaceWordTo, RegexOptions.None);  

      



If you want, you can make a separate method to automatically add tags \b

to your string:

private string AddEscapeTags(string wordYouWantToReplace)
{
    return string.Format(@"\b{0}\b", wordYouWantToReplace);
}

      

Then you can simply call string yourInputString = AddEscapeTags("Hello");

+2


source







All Articles