【问题标题】:How to replace a character in C# string ignoring other characters?如何替换 C# 字符串中的字符而忽略其他字符?
【发布时间】:2020-12-12 17:33:38
【问题描述】:

假设我有以下字符串:

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

我想用 "&" 替换 "&"(b/w a 和 b)

所以,如果我使用

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

它还将替换与<> 关联的“&”。

有什么方法可以只替换 a 和 b 之间的“&”吗?

【问题讨论】:

  • 与所有字符串编码的情况一样,您应该知道原始字符串采用什么格式来实现正确的功能。例如,原始字符串是“原始字符串”还是“带有 HTML 实体的字符串”? answer by Karan 仅适用于后者。
  • Karan 的回答很好,但您首先应该尽量避免这种情况。你是如何得到一个混合了 html 实体和未编码 & 符号的字符串的?您能否在与 < 结合之前对 & 进行编码?
  • @ComFreek:与 SO 上的许多编码问题一样,我认为您的问题的答案是:“原始字符串是 HTML 编码和非 HTML 编码字符串的任意组合由不知道自己在做什么的人创建,我的任务是在稍后阶段“修复它”。我知道这在一般情况下是不可能的,所以请提供适用于大多数情况的 hack 和我会祈祷最终巧妙地打破它的边缘案例只有在我离开公司后才会出现”。

标签: c#


【解决方案1】:

您可以使用HttpUtility.HtmlEncodeHttpUtility.HtmlDecode,如下所示。

首先解码您的字符串以获得普通字符串,然后再次对其进行编码,这将为您提供预期的字符串。

HttpUtility.HtmlEncode(HttpUtility.HtmlDecode("hello a & b, &lt;hello world &gt;"));
  • HttpUtility.HtmlDecode("hello a &amp; b, &amp;lt;hello world &amp;gt;") 将返回 hello a &amp;amp; b, &amp;lt;hello world &amp;gt;

  • HttpUtility.HtmlEncode("hello a &amp; b, &lt;hello world &gt;") 将返回 hello a &amp;amp; b, &amp;lt;hello world &amp;gt;

【讨论】:

【解决方案2】:

您可以尝试在搜索字符串的字符两边添加空格:

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

【讨论】:

  • 字符串开头或结尾处的&amp;怎么样?
  • 您建议的内容可用于此特定字符串。实际上,正如 Ilya 所提到的,情况可能非常不同。
【解决方案3】:

我想你可以使用正则表达式:

Regex.Replace("hello a & b, &lt;hello world &gt;", "&(?![a-z]{1,};)", "&amp;");
  • & 匹配文字 &
  • (?!) 否定前瞻(断言以下不匹配)
  • [a-z]{1,}; 任意字符 a-z,一次或多次,后跟一个 ';'

【讨论】:

    【解决方案4】:
    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;amp; b, &amp;lt;hello world&amp;gt;

    【讨论】:

    【解决方案5】:

    我认为@afrischke 的回答已经足够好了。但它可能有点过于严格。如果您只想忽略 &lt 和 &gt,您可以使用以下内容。

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

    &(?!(lt|gt);) :文字“&”,后面不跟“lt;”或“gt;”。

    【讨论】:

      猜你喜欢
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-08
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多