【问题标题】:How can I strip any and all HTML tags from a string? [duplicate]如何从字符串中去除任何和所有 HTML 标记? [复制]
【发布时间】:2015-10-07 18:42:35
【问题描述】:

我有一个这样定义的字符串:

private const String REFER_TO_BUSINESS = "<pre> (Refer to business office for guidance and explain below the circumstances for exception to policy or attach a copy of request)</pre>";

...如您所见,它具有“pre”标签,用于保留前面的空格。不过,我想在没有“pre”标签的情况下引用这个字符串。搜索 "

" 和 "
" 并删除它们很容易,但对每种 HTML 标记类型都这样做很快就会变得乏味。

如何在 C# 中从字符串中去除所有标签,无论它们是“

”、“

”、“”、“

【问题讨论】:

  • 这是迄今为止答案中正则表达式实现的问题 - 它们破坏了不包含任何 HTML 标记的 x &amp;lt; 6 &amp;amp;&amp;amp; y &amp;gt; 8 之类的字符串。
  • 好点,但不适用于我的用例。
  • @jdphenix 也许是因为要成为有效的 html,你的字符串应该是 x &amp;lt; 6 &amp;amp;&amp;amp; y &amp;gt; 8
  • @B.ClayShannon Good point, but doesn't apply to my use case. 如果您的情况总是像您的问题一样简单,那么您可以使用它,但这不是获取html标签之间文本的正确方法。使用 Html 解析器,例如 HtmlAgilityPack。
  • @EZI 好的 - 你找到我了。没有一个测试用例,因为它是有效的 HTML 并且正则表达式解决方案不起作用。就是……臭。 :)

标签: c# html


【解决方案1】:

尝试正则表达式替换。 此模式匹配字符串中的 html 标记。来自here

        var pattern = @"</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>";
        var source = "<pre> (Refer to business office for guidance and explain below the circumstances for exception to policy or attach a copy of request)</pre>";
        Regex.Replace(source, pattern, string.Empty);

【讨论】:

    【解决方案2】:

    这应该做你需要做的事情:

     string stripMeOfHTML = Regex.Replace(stripMeOfHTML, @"<[^>]+>", "").Trim();
    

    【讨论】:

      【解决方案3】:

      这行得通:

      // For strings that have embedded HTML tags for presentation on the form (such as "<pre>" and such), but need to be rendered free of these (such as on the PDF)
      private String RemoveHTMLTags(String stringContainingHTMLTags)
      {
          String regexified = Regex.Replace(stringContainingHTMLTags, "<.*?>", string.Empty);
          return regexified;
      }
      

      【讨论】:

        猜你喜欢
        • 2010-10-21
        • 2011-06-27
        • 2015-10-09
        • 2016-03-28
        • 2013-02-21
        • 2012-08-07
        • 2012-03-14
        • 2014-11-16
        相关资源
        最近更新 更多