2013-08-25 35 views
-1

我有字符串<strong>Foo</strong>。我想從這個字符串中刪除HTML標籤,即使它的內容。在這個例子中,表達式必須返回""(空字符串)。我應該怎麼做?如何在Java中刪除HTML及其內容?

+0

你的意思是'null',或者你的意思是一個空字符串'「」 '? – jlordo

+0

可能會被複制http://stackoverflow.com/questions/1265282/recommended-method-for-escaping-html-in-java –

+0

我的意思是空的。 – Tony

回答

2

如果您試圖刪除的html沒有任何嵌套的html標籤;這是一個簡單的基於正則表達式的解決方案。您可以將標籤名稱分配給tag以方便使用,並且正則表達式會相應地進行調整。

String tag = "strong"; 
String str = "This is <strong>Foo</strong>Bar."; 

String regex = "<\\s*" + tag + "[^>]*>[^<]*</\\s*" + tag + "\\s*>"; 

System.out.println(str.replaceAll(regex, "")); // This is Bar. 

正則表達式可容納任何額外的標籤屬性,如<strong class="bold">但如果可能會破壞並更新照顧有點不舒服,HTML格式的像不必要的空格或新線在這裏和那裏。

0

既然你聲稱你沒有嵌套的標籤,你可以嘗試使用"<([^>]+)>.*?</\\1>

String data = "bar<strong>foo</strong>yyy<strong>zzz</strong>"; 
System.out.println(data.replaceAll("<([^>]+)>.*?</\\1>", "")); 

ouptut

baryyy 
+0

@downvoter謹慎地解釋你的行爲? – Pshemo

相關問題