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, &lt;hello world &gt;") will return hello a & b, <hello world >.

  • HttpUtility.HtmlEncode("hello a & b, <hello world >") will return hello a &amp; b, &lt;hello world &gt;


You could use regex, I suppose:

Regex.Replace("hello a & b, &lt;hello world &gt;", "&(?![a-z]{1,};)", "&amp;");
  • & 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 ';'

Tags:

C#