Search and Match exact strings

Hi, I'm trying to search and replace a certain string such but only when the string is by itself, for example when st is by itself it wants to be replaced with stop. I have this working after using the top example here: http://ift.tt/1FloepQ

I have now found an issue when trying to match on a word that contains a regex special character, I am trying to match on br$ but due to $ being a regex special character the match fails. I have modified my extension method to be the following:

public static string SafeReplace(this string input, string find, string replace, bool matchWholeWord) { var escapedFind = Regex.Escape(find.Trim()); string textToFind = matchWholeWord ? string.Format(@"\b{0}\b", escapedFind) : escapedFind; var newtext = Regex.Replace(input.Trim(), textToFind, replace) + " "; return newtext; } 

This still doesn't seem to work, if I remove the \b (the regex word boundary character) it seems to work but this obviously stops it matching on strings that are only by themselves.

Can anyone help me out?

Cheers

by tomaustin700 via /r/csharp

Leave a Reply