asp.net - How to replace special characters using regex -
using asp.net regex.
i've written extension method want use replace whole words - word might single special character '&'.
in case want replace '&' 'and', , i'll need use same technique reverse 'and' '&', must work whole words , not extended words 'hand'.
i've tried few variations regex pattern - started '\bword\b' didn't work @ ampersand, , have '\sword\s' works except removes spaces around word, meaning phrase "health & beauty" ends "healthandbeauty".
any appreciated.
here's extension method:
public static string replaceword(this string @this, string wordtofind, string replacement, regexoptions regexoptions = regexoptions.none) { guard.string.notempty(() => @this); guard.string.notempty(() => wordtofind); guard.string.notempty(() => replacement); var pattern = string.format(@"\s{0}\s", wordtofind); return regex.replace(@this, pattern, replacement, regexoptions); }
in order match dynamic string should enclosed spaces (or located @ start or end of string), can use negative lookaheads:
var pattern = string.format(@"(?<!\s){0}(?!\s)", wordtofind); ^^^^^^^ ^^^^^^
or safer:
var pattern = string.format(@"(?<!\s){0}(?!\s)", regex.escape(wordtofind)); ^^^^^^^^^^^^^
the (?<!\s)
lookbehind fail match if word not preceded non-whitespace character , (?!\s)
lookahead fail match if word not followed non-whitespace character.
Comments
Post a Comment