Reputation:
I have Two string
string One="This is StackOverFlow, Thisis StackOverFlow, Thisis";
string Two="Hello HelloHello Hello This is StackOverFlow!"
I want to replace Every separate This is to Hello Everyone In for string One,
And every separate Hello to Hello Everyone In for string Two
i try 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 given string, but it replacing HelloHello too, and HelloHello is differ value for my program so it have to be in original form.
In string One, Thisis is considered as a differ string but Why in string Two it considering HelloHello as Hello repetition
can anyone have a solution for this?
Sorry for my bad english
Upvotes: 3
Views: 88
Reputation: 1396
You have to make sure you check on exact words. \b
ensures that you only look at the exact matches and not matches that are part of different words. As the docs explain it:
The match must occur on a boundary between a \w (alphanumeric) and a \W (nonalphanumeric) character.
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 seperate method to automatically add the \b
tags to your string:
private string AddEscapeTags(string wordYouWantToReplace)
{
return string.Format(@"\b{0}\b", wordYouWantToReplace);
}
Then you can just call string yourInputString = AddEscapeTags("Hello");
Upvotes: 2