Come sostituire un carattere nella stringa C # ignorando altri caratteri?

Aug 23 2020

Considera che ho una stringa seguente:

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

Voglio sostituire "&"(b / wa eb) con"&"

Quindi, se uso

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

Sostituirà anche "&" associato a <e >.

C'è un modo per sostituire solo "&" tra a e b?

Risposte

57 Karan Aug 24 2020 at 04:57

Puoi piuttosto usare HttpUtility.HtmlEncode& HttpUtility.HtmlDecodecome sotto.

Prima decodifica la tua stringa per ottenere una stringa normale, quindi codificala di nuovo che ti darà la stringa prevista.

HttpUtility.HtmlEncode(HttpUtility.HtmlDecode("hello a & b, <hello world >"));
  • HttpUtility.HtmlDecode("hello a & b, &lt;hello world &gt;")tornerà hello a & b, <hello world >.

  • HttpUtility.HtmlEncode("hello a & b, <hello world >") sarà di ritorno hello a &amp; b, &lt;hello world &gt;

6 afrischke Aug 25 2020 at 02:31

Potresti usare regex, suppongo:

Regex.Replace("hello a & b, &lt;hello world &gt;", "&(?![a-z]{1,};)", "&amp;");
  • & abbina letterale &
  • (?!) lookahead negativo (asserisci che quanto segue non corrisponde)
  • [az] {1,}; qualsiasi carattere az, una o più volte, seguito da un singolo ";"
Razack Aug 24 2020 at 05:15

Puoi provare ad aggiungere spazi su entrambi i lati del carattere nella stringa di ricerca:

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

produzione:

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

HainanZhao Aug 31 2020 at 02:50

Penso che la risposta di @ afrischke sia abbastanza buona. Ma potrebbe essere un po 'troppo restrittivo. Nel caso in cui desideri ignorare solo & lt e & gt, puoi utilizzare quanto segue.

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

& (?! (lt | gt);): letterale "&" che non è seguito da "lt;" o "gt;".