1

I'm trying to work out how to use the Regex.Replace method for my needs, basically I need to find a particular word which doesn't have any "a-z" letters either side of it and replace only the matches with another word.

In the example below I search for all "man" occurrences and replace with "coach". I use this regex pattern "[^a-z](man)[^a-z]" which does capture what I want.

//String to search
"The man managed the football team"

//After using Regex.Replace I expect to see
"The coach managed the football team"

//But what I actually get is
"The coach coachaged the football team"
3
  • What about testing if it has a space in front or after \sman\s ? Commented Jun 26, 2015 at 12:13
  • Can you please produce a MVCE since using the regex you've provided will not replace managed for me. Commented Jun 26, 2015 at 12:13
  • Regex.Replace("The man managed the football team", "[^a-z](man)[^a-z]", "coach") => Thecoachmanaged the football team, because you also replace the spaces around man. Commented Jun 26, 2015 at 12:15

1 Answer 1

4

You need \b aka word boundary.

\b assert position at a word boundary (^\w|\w$|\W\w|\w\W)

Use \bman\b

See demo.

https://regex101.com/r/yG7zB9/31

Your regex will replace 5 characters always.\b is a 0 width assertion so it doesnt consume a character.

string strRegex = @"\bman\b";
Regex myRegex = new Regex(strRegex, RegexOptions.Multiline);
string strTargetString = @"The man managed the football team";
string strReplace = @"coach";

return myRegex.Replace(strTargetString, strReplace);
Sign up to request clarification or add additional context in comments.

6 Comments

Considering his original regular expression does indeed do what he wants (though yours is obviously better), I'm not entirely sure we've seen the entire question yet.
@LasseV.Karlsen OP's regex replaces <1 character>man<` character> so in effect it will never replace man but 5 characters which has man in between
Yes, you're right. Let me rephrase, it will not touch managed.
Hi, I have tried var res = Regex.Replace(str, "\bman\b", "coach");
Perfect thank you "var res = Regex.Replace(str, @"\bman\b", "coach");" worked
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.