How to replace a character in C# string ignoring other characters?

Viewed 3014

Consider that I have a following string:

string s = "hello a & b, <hello world >"

I want to replace "&" (b/w a and b) with "&"

So, if I use

s.replace("&", "&");

It will also replace "&" associated with < and >.

Is there any way I can replace only "&" between a and b?

5 Answers

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 ';'

You can try adding spaces on both sides of the character in the search string:

s.replace(" & ", " &amp;");
string s = "hello a & b, &lt;hello world&gt;";
var sd =  s.Replace("&lt;", "<").Replace("&gt;", ">");
var e = HttpUtility.HtmlEncode(sd);
WriteLine(e);

output:

hello a &amp; b, &lt;hello world&gt;

I think @afrischke's answer is good enough. But it may be a little too restrictive. In case you only want to ignore &lt and &gt, you can use the following.

Regex.Replace("hello a & b, &lt;hello world &gt;", "&(?!(lt|gt);)", "&amp;");

&(?!(lt|gt);) : Literal "&" which is not followed by "lt;" or "gt;".

Related