I want to replace some words in text, but only on conditions as, for example, if each is surrounded by whitespace.
To do this, I use:
Regex rx = Regex(@"\s+" + word + @"\s+");
str = rx.Replace(str, word2);
In the end, I get spaces replaced as well (and all the other specified surroundings). How can this be bypassed?
You can use the
\banchor to match the boundary between a\w(alphanumeric) and a\W(non-alphanumeric) character.: