Regex replace only matched strings - C# -
i'm trying work out how use regex.replace method needs, need find particular word doesn't have "a-z" letters either side of , replace matches word.
in example below search "man" occurrences , replace "coach". use regex pattern "[^a-z](man)[^a-z]
" capture want.
//string search "the man managed football team" //after using regex.replace expect see "the coach managed football team" //but "the coach coachaged football team"
you need \b
aka word boundary
.
\b assert position @ word boundary (^\w|\w$|\w\w|\w\w)
use \bman\b
see demo.
https://regex101.com/r/yg7zb9/31
your regex replace 5
characters always.\b
0 width assertion
doesnt consume character.
string strregex = @"\bman\b"; regex myregex = new regex(strregex, regexoptions.multiline); string strtargetstring = @"the man managed football team"; string strreplace = @"coach"; return myregex.replace(strtargetstring, strreplace);
Comments
Post a Comment