【问题标题】:How to remove all comments in a HTML String [duplicate]如何删除 HTML 字符串中的所有注释 [重复]
【发布时间】:2015-09-07 12:51:31
【问题描述】:

我有一个String,它在<! --> 内有cmets,即<!comment1-->。 我想删除所有这些。

RE 是什么?

我试过了:

replaceAll("\\<!.*?\\-\\-\\>", "");

但它没有用。 我尝试循环和替换,它可以工作,但我正在寻找一个正则表达式

我已经尝试过该墨水中提到的 html.fromHtml 并且它不起作用。为此我提出了另一个问题here

例如下面的字符串

<style> <!-- /* Font Definitions */ @font-face  {font-family:"Cambria Math";    panose-1:2 4 5 3 5 4 6 3 2 4;} @font-face       {font-family:Calibri;   panose-1:2 15 5 2 2 2 4 3 2 4;} @font-face      {font-family:Tahoma;    panose-1:2 11 6 4 3 5 4 4 2 4;} @font-face      {font-family:Webdings;  panose-1:5 3 1 2 1 5 9 6 7 3;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal         {margin:0in;    margin-bottom:.0001pt;  font-size:11.0pt;       font-family:"Calibri",sans-serif;} a:link, span.MsoHyperlink    {mso-style-priority:99;         color:#0563C1;  text-decoration:underline;} a:visited, span.MsoHyperlinkFollowed        {mso-style-priority:99;         color:#954F72;  text-decoration:underline;} span.EmailStyle17   {mso-style-type:personal-compose;       font-family:"Calibri",sans-serif;       color:windowtext;} .MsoChpDefault       {mso-style-type:export-only;    font-family:"Calibri",sans-serif;} @page WordSection1   {size:8.5in 11.0in;     margin:1.0in 1.0in 1.0in 1.0in;} div.WordSection1       {page:WordSection1;} --></style>

【问题讨论】:

标签: java android regex string


【解决方案1】:

确保您收到来自String.replaceAll 的返回值。

String html = "abcde<!--comment1-->\n"
        + "<p>abcdefghi<!--comment2-->jkl</p>\n"
        + "<p>abcdefghi<span>jklm<!--comment3-->nopq</span>rs</p>\n";

String commentsRemoved = html.replaceAll("<!--.*?-->", "");

System.out.println(html);
System.out.println(commentsRemoved);

【讨论】:

  • 相当有效的html:&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt;&lt;head&gt;&lt;title&gt;&lt;!-- aaa&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;a href=""&gt;aaaa--&gt;&lt;/a&gt;&lt;script &gt;window.title = "--&gt;";&lt;/script&gt;--&gt;aaaa aaaa&lt;!-- aaaa //--&gt; &lt;script &gt;window.title = "--&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;
  • 这个答案很好用。
【解决方案2】:
    Try this
 string ss = "<b><i>The tag is about to be removed</i></b>";
    Regex regex = new Regex("\\<[^\\>]*\\>");
    Response.Write(String.Format("<b>Before:</b>{0}", ss)); // HTML Text
    Response.Write("<br/>");
    ss = regex.Replace(ss, String.Empty);
    Response.Write(String.Format("<b>After:</b>{0}", ss));// Plain Text as a  OUTPUT

【讨论】:

  • 删除所有标签和文本会丢失格式。我只想删除 cmets,然后使用 fromHtml 。这个我试过了
猜你喜欢
  • 2018-01-01
  • 2015-10-09
  • 1970-01-01
  • 2018-06-24
  • 2013-08-05
  • 2015-08-29
  • 1970-01-01
  • 2019-09-28
  • 1970-01-01
相关资源
最近更新 更多