2014-06-10 78 views
2

我有一個模式來匹配像僅匹配「<span>東西</span>行尾」,而不是「<span>東西</span></span>」

... 
<span class="count">1036</span> 
... 

但我並不想匹配

<span class="count">1036</span></span> 

因爲它會趕上

1036</span> 

但無論如何,我不想趕上雙倍,因爲我不需要這些數據。 我需要跨度和行尾之間的數據。

我\ n試圖在跨度的結束,但它沒有工作...... 這裏的模式:

private static final Pattern COUNT = Pattern.compile("<span class=\"count\">(.+?)</span> "); 

謝謝你的答案

+0

我會改變'+'它匹配任何東西'[?^<] +'這會馬上tch不是' pavlindrom

+2

永遠不要使用正則表達式來解析html。使用html解析器 – jackcogdill

回答

0

爲「正則表達式代碼行尾「爲$

嘗試:行

private static final Pattern COUNT = Pattern.compile("<span class=\"count\">(.+?)</span>$ "); 
+0

這並不能解決問題,catch組仍然可以匹配''。 – pavlindrom

+0

是的,你是對的,它肯定會要求否定一個開角尖括號。 – Woodham

0

使用多線路開關(?m),這使得^和$匹配的開始/結束。

Pattern COUNT = Pattern.compile("(?m)<span class=\"count\">(.+?)</span>$"); 
0

嘗試用封閉的括號()內的正則表達式的分組功能,它使用Matcher#group(1)得到。

正則表達式

<span class="count">([^<]*?)</span> 

DEMO

示例代碼:

Pattern pattern = Pattern.compile("<span class=\"count\">([^<]*?)</span>"); 
Matcher matcher = pattern.matcher("<span class=\"count\">1036</span></span>"); 
while (matcher.find()) { 
    System.out.println(matcher.group(1)); 
} 

輸出:

1036 
+0

查找類似問題[here](http://stackoverflow.com/questions/24124033/split-string-by-tag-java) – Braj

相關問題