【问题标题】:In C#, how can I replace\u0026 with &?在 C# 中,如何用 & 替换 \u0026?
【发布时间】:2015-09-11 01:43:29
【问题描述】:

我在我的 C# 代码中得到一个来自一些 javascript 序列化的字符串,我看到一堆这样的字符串:

  Peanut Butter \u0026 Jelly

我试过这样做:

  string results  = resultFromJsonSerialization();
  results = results.Replace("\u0026", "&");
  return results;

我希望它会变成:

 Peanut Butter & Jelly

但它似乎没有进行替换。在 C# 中进行这种替换的正确方法是什么?

【问题讨论】:

  • 使用另一个反斜杠来转义该反斜杠。 “\\u0026”实际上是“\u0026”
  • 或者您可以使用字符串文字符号,例如@"\u0026".
  • @RobSchmuecker 在这里没有冒犯,但你为什么不将此问题标记为重复?
  • @AndreasNiedermair 不幸的是,我对 C# 还不够熟悉,无法做出这种区分!

标签: javascript c# serialization replace


【解决方案1】:

将其标记为文字

results.Replace(@"\u0026", "&");

【讨论】:

    【解决方案2】:

    您可以使用正则表达式 Unescape() 方法。

      string results  = resultFromJsonSerialization();
      results = System.Text.RegularExpressions.Regex.Unescape(results);
      return results;
    

    您还可以利用服务器实用程序进行 HTML 编码。

      results = ControllerContext.HttpContext.Server.HtmlDecode(results);
    

    【讨论】:

    • Regex.Unescape 是有效答案
    • 在找到这个之前,我搜索了互联网。谢谢!
    猜你喜欢
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多