如題:
使用正則表達式,怎么匹配特定html標簽內(nèi)的內(nèi)容。
比如,對于如下文本串:
... ignored content
prefix content
<html>inner content</html>
postfix content
... ignored content
我們要提取出<html>標簽內(nèi)的內(nèi)容: inner content(這里的html標簽可以換成任何其它的標簽,比如<p>標簽)
這里引入正則表達式的group概念:詳細點擊文章查看
比如:對于一個正則表達式( ( A ) ( B ( C ) ) )
- group 1為:( ( A ) ( B ( C ) ) )
- group 2為:( A )
- group 3為:( B ( C ) )
- group 4為:( C )
這樣,我們就能夠構(gòu)造出如下的正則表達式:.*(<(html>)(.*)</\2).*
此表達式的group概念為:
- group 1: (<(html>)(.*)</\2)
- group 2: (html>)
- group 3: (.*)
顯然我們要求的就是group3的內(nèi)容。
注意:\2是對group2的引用,也就是html>
該正則表達式也可以寫成: .*(<(html>)(.*)</(html>)).*
化簡其實就是.*<html>(.*)</html>.*
代碼實現(xiàn)為:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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!" ); } |
總結(jié)
到此這篇關(guān)于Java正則表達式如何匹配特定html標簽內(nèi)容的文章就介紹到這了,更多相關(guān)Java正則表達式匹配html標簽內(nèi)容內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/qq_37206105/article/details/108323320