How to replace a character in C# string ignoring other characters?
You can rather use HttpUtility.HtmlEncode
& HttpUtility.HtmlDecode
like below.
First decode your string to get normal string and then encode it again which will give you expected string.
HttpUtility.HtmlEncode(HttpUtility.HtmlDecode("hello a & b, <hello world >"));
HttpUtility.HtmlDecode("hello a & b, <hello world >")
will returnhello a & b, <hello world >
.HttpUtility.HtmlEncode("hello a & b, <hello world >")
will returnhello a & b, <hello world >
You could use regex, I suppose:
Regex.Replace("hello a & b, <hello world >", "&(?![a-z]{1,};)", "&");
- & match literal &
- (?! ) negative lookahead (assert that the following does not match)
- [a-z]{1,}; any char a-z, one or more times, followed by a single ';'