1. 程式人生 > 程式設計 >Java正則表示式如何匹配特定html標籤內的內容

Java正則表示式如何匹配特定html標籤內的內容

如題:

使用正則表示式,怎麼匹配特定html標籤內的內容。

比如,對於如下文字串:

... ignored content
prefix content
<html>inner content</html>
postfix content
... ignored content

我們要提取出<html>標籤內的內容: inner content(這裡的html標籤可以換成任何其它的標籤,比如<p>標籤)

這裡引入正則表示式的group概念:詳細點選文章檢視

比如:對於一個正則表示式( ( A ) ( B ( C ) ) )

  • group 1為:( ( A ) ( B ( C ) ) )
  • group 2為:( A )
  • group 3為:( B ( C ) )
  • group 4為:( C )

這樣,我們就能夠構造出如下的正則表示式:.*(<(html>)(.*)</\2).*

此表示式的group概念為:

  • group 1: (<(html>)(.*)</\2)
  • group 2: (html>)
  • group 3: (.*)

顯然我們要求的就是group3的內容。

注意:\2是對group2的引用,也就是html>

該正則表示式也可以寫成: .*(<(html>)(.*)</(html>)).*

化簡其實就是.*<html>(.*)</html>.*

程式碼實現為:

String p = ".*(<(html>)(.*)</\\2).*";
String m = "prefix<html>午休abc</html>postfix";

System.out.println("Pattern: " + p);
System.out.println("String to be test: " + m);

Pattern pattern = Pattern.compile(p);
Matcher matcher = pattern.matcher(m);
if(matcher.matches()) {
 System.out.println("Matched String: " + matcher.group(3));
} else {
 System.out.println("So sad,not matching anything!");
}

總結

到此這篇關於Java正則表示式如何匹配特定html標籤內容的文章就介紹到這了,更多相關Java正則表示式匹配html標籤內容內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!