他の文字を無視してC#文字列の文字を置き換える方法は?

Aug 23 2020

次の文字列があると考えてください。

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

"&"(b / waとb)をに置き換えたい"&"

だから、私が使うなら

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

また、<およびに関連付けられた「&」も置き換えられ>ます。

aとbの間の「&」のみを置き換える方法はありますか?

回答

57 Karan Aug 24 2020 at 04:57

以下のHttpUtility.HtmlEncode&HttpUtility.HtmlDecodelikeを使用できます。

最初に文字列をデコードして通常の文字列を取得してから、もう一度エンコードすると、期待される文字列が得られます。

HttpUtility.HtmlEncode(HttpUtility.HtmlDecode("hello a & b, <hello world >"));
  • HttpUtility.HtmlDecode("hello a & b, &lt;hello world &gt;")を返しhello a & b, <hello world >ます。

  • HttpUtility.HtmlEncode("hello a & b, <hello world >") 戻ります hello a &amp; b, &lt;hello world &gt;

6 afrischke Aug 25 2020 at 02:31

正規表現を使用できます。

Regex.Replace("hello a & b, &lt;hello world &gt;", "&(?![a-z]{1,};)", "&amp;");
  • リテラルに一致&
  • (?!)ネガティブ先読み(以下が一致しないことを主張)
  • [az] {1、}; 任意の文字az、1回以上、その後に1つの ';'が続く
Razack Aug 24 2020 at 05:15

検索文字列の文字の両側にスペースを追加してみてください。

s.replace(" & ", " &amp;");
ANSerpen Aug 25 2020 at 20:07
string s = "hello a & b, &lt;hello world&gt;";
var sd =  s.Replace("&lt;", "<").Replace("&gt;", ">");
var e = HttpUtility.HtmlEncode(sd);
WriteLine(e);

出力:

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

HainanZhao Aug 31 2020 at 02:50

@afrischkeの答えで十分だと思います。しかし、それは少し制限が強すぎるかもしれません。&ltと&gtのみを無視したい場合は、以下を使用できます。

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

&(?!(lt | gt);):「lt;」が後に続かないリテラル「&」または「gt;」。