Regex replace specified text

I want to replace some words in the text, but only on conditions, for example, if each of them is surrounded by spaces.

For this, I use:

Regex rx = Regex(@"\s+" + word + @"\s+"); str = rx.Replace(str, word2); 

In the end, I also replaced the spaces (and all other specified environments). How can I get around this?

+4
source share
3 answers

You can use the \b binding to match the border between \w (alphanumeric) and \w (non-alphanumeric) .:

 Debug.Assert(Regex.Match(word, "^\w+$").Success); string result = Regex.Replace(input, @"\b" + word + @"\b", word2); 
+5
source
 str = Regex.Replace(str ,@"(?<first>\s+)" + word + @"(?<last>\s+)","${first}" + word2 + "${last}"); 
+1
source

A regular expression looks good for the pattern you are describing. I use Expresso to validate my regex patterns. There is also RegExr , an online tool.

0
source

All Articles