簡體   English   中英

如何使用正則表達式從Java中的字符串中刪除一些html標記

[英]How to use regular expressions to remove some html tags from string in java

我寫了一個代碼來從XML文件(Feed)中讀取新聞。.,我必須在列表視圖中顯示每個項目的描述...,我使用了這段代碼來刪除description標記中存在的html標記:

else if ("description".equals(tagName)){
                             sourcedescription= parser.nextText();
                             description=Html.fromHtml(sourcedescription).toString();
                             Log.d("msg", description);
                             feedDescription.add(description);

                         }

有些項目我成功地顯示了沒有標簽的描述,即以一種易於理解的方式,但是我未能刪除具有{iframe} {/ iframe}標簽的其他一些項目的所有標簽...,我認為此標簽存在於描述標簽中沒有“描述”的項目

<description><![CDATA[<p>{iframe height="600"}<a href="http://admreg.yu.edu.jo/index.php?option=com_content&view=article&id=606:------20132014&catid=87:2011-01-25-18-12-08&Itemid=438">http://admreg.yu.edu.jo/index.php?option=com_content&view=article&id=606:------20132014&catid=87:2011-01-25-18-12-08&Itemid=438</a><span style="line-height: 1.3em;">{/iframe}</span></p>]]></description>

我的問題是如何使用正則表達式刪除iframe廣告代碼?

可能的解決方案是

    String regexp = "\\{/?iframe.*?\\}";
    String text = "<description><![CDATA[<p>{iframe height=\"600\"}<a href=\"http://admreg.yu.edu.jo/index.php?option=com_content&view=article&id=606:------20132014&catid=87:2011-01-25-18-12-08&Itemid=438\">http://admreg.yu.edu.jo/index.php?option=com_content&view=article&id=606:------20132014&catid=87:2011-01-25-18-12-08&Itemid=438</a><span style=\"line-height: 1.3em;\">{/iframe}</span></p>]]></description>";
    System.out.println(text.replaceAll(regexp, ""));

如果要刪除代碼iframe內的內容,請改用此regexp:

text.replaceAll("\\{iframe .*?\\}.*?\\{/iframe\\}", "")

使用以下正則表達式:

\{iframe[^\}]*\}   // to delete the opening tag
\{/iframe[^\}]*\}  // to delete the closing tag

這些正則表達式不會刪除iframe中的內容。

注意 :如果有選擇, 使用解析器。 那就是...為了快速又骯臟..

str.replaceAll("\\{/?iframe.*?\\}", "");

刪除這些標簽之間的內容。

str.replaceAll("\\{iframe.*?\\}.*?\\{/iframe\\}", "")

HTML不是常規語言。 不要將其與RegEx一起使用,否則會死掉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM