2013-01-02 161 views
0

可能重複:
How to remove HTML tag in Java
RegEx match open tags except XHTML self-contained tagsJAVA正則表達式來刪除HTML標記和內容

我想刪除特定HTML標籤的內容。

例如,如果HTML:

<span style='font-family:Verdana;mso-bidi-font-family: 
"Times New Roman";display:none;mso-hide:all'>contents</span> 

如果標籤包含 「mso- *」,它必須刪除整個標籤(開,關,內容)。

+10

個人而言,我會使用HTML解析器。 –

+2

[RegEx match open tags not except XHTML self-contained tags](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags)可能的重複和[how -to-remove-html-tag-in-java](http://stackoverflow.com/questions/1699313/how-to-remove-html-tag-in-java) – CoolBeans

+0

這些類型的問題沒有被問到很多次在這裏? –

回答

0

由於Dave Newton在他的評論中指出,一個html解析器是去這裏的路。如果你真的想要做到這一點,這裏是一個正則表達式:

String html = "FOO<span style='font-family:Verdana;mso-bidi-font-family:" 
     + "\"Times New Roman\";display:none;mso-hide:all'>contents</span>BAR"; 
    // regex matches every opening tag that contains 'mso-' in an attribute name 
    // or value, the contents and the corresponding closing tag 
    String regex = "<(\\S+)[^>]+?mso-[^>]*>.*?</\\1>"; 
    String replacement = ""; 
    System.out.println(html.replaceAll(regex, replacement)); // prints FOOBAR 
+0

如果style屬性不包含任何'mso-'指令......也許更爲廣義的正則表達式就是按順序排列的。 – pap

+0

@pap讓我引用OP:_If標籤包含「mso- *」,它必須刪除整個標籤(開啓,關閉和內容)._我的帖子回答他的問題,我不明白您的意見。 – jlordo

+0

確實你是對的。對我沒有正確閱讀的問題感到羞恥:)而且我認爲你低估了自己,你似乎已經理解我的評論就好,只是我錯了;) – pap

相關問題