2015-10-07 62 views
0

我有一個字符串,如分開的匹配數量:正則表達式上的一串數字由空格

String s = " 10 5 15 55 5 "; 

,我試圖讓一些重複的次數(在此案例5),使用一個RegExp,所以我的做法是這樣的:

long repetitions = s.split(" 5").length -1; 

,但是這是行不通的,這也符合55

如果我使用的數量兩側的空間,像:

String s=" 10 10 15 5 "; 
long repetitions = s.split(" 10 ").length -1; 

它不起作用,它只計算10(我有兩個)的一個實例。

所以我的問題是哪個regExp可以正確計數兩種情況?

+0

您可以嘗試使用split(「\\ b5 \\ b」)' 。 – Pshemo

+1

@Codebender可能是因爲'_10_10_'之間的空間正被第一個'_10_'消耗,這阻止了第二個'_10_'的匹配(因爲它的開始處的空間不能再次匹配 - 這可以通過環視來解決,但是'\ b'更簡單)。 – Pshemo

+0

這工作正常,謝謝。 但是,能否請你解釋一下爲什麼它會起作用,我是regExp的新手,我想知道他們是如何工作的 –

回答

1

您可以使用模式匹配與使用word-boundaries去尋找5的是不是別的東西」的一部分,正則表達式'\b5\b'

String s = " 10 5 15 55 5 "; 
Pattern p = Pattern.compile("(\\b5\\b)"); 
Matcher m = p.matcher(s); 
int countMatcher = 0; 
while (m.find()) { // find the next match 
    m.group(); 
    countMatcher++; // count it 
} 
System.out.println("Number of matches: " + countMatcher); 

輸出

Number of matches: 2 

您可以對10等進行相同操作。

相關問題