2010-01-11 135 views

回答

2

您可以在循環中使用find方法進行計數。有一個在Java tutorial一個例子:

import java.util.regex.Pattern; 
import java.util.regex.Matcher; 

public class MatcherDemo { 

    private static final String REGEX = "\\bdog\\b"; 
    private static final String INPUT = "dog dog dog doggie dogg"; 

    public static void main(String[] args) { 
     Pattern p = Pattern.compile(REGEX); 
     Matcher m = p.matcher(INPUT); // get a matcher object 
     int count = 0; 
     while(m.find()) { 
      count++; 
      System.out.println("Match number "+count); 
      System.out.println("start(): "+m.start()); 
      System.out.println("end(): "+m.end()); 
     } 
    } 
} 

當你調用find,你可以在同一時間收集字符串的零部件和手動構建導致StringBuffer。或者,如果性能不是問題,則可以先進行計數,然後再用replaceAll再次掃描字符串。

+0

沒有循環可以找到在同一拍攝。因爲它可能會降低性能。 – GuruKulki 2010-01-11 07:39:59

+4

即使有一個函數可以在沒有循環的情況下調用,在內部它仍然會有一個循環,所以我認爲你不會看到顯着的性能改進。由於字符串只被掃描一次,所以上面列出的第一種方法應該能夠提供良好的性能。以上答案可能是 – 2010-01-11 07:43:07

1

,而不是你可以做:

int num = 0; 
Pattern keyPattern = Pattern.compile(key); 
Matcher matcher = keyPattern.matcher(str); 
while(matcher.find()){ 
    str = matcher.replaceFirst(); 
    matcher = keyPattern.matcher(str); //don't know if this line is necessary 
    num++; 
} 
+0

更好。 – 2010-01-11 07:33:34

+1

同意。首先,您的解決方案必須每次都從頭開始重新掃描。其次,如果(例如)替換字符串包含與鍵模式匹配的內容,它將給出錯誤的答案。 – 2010-01-11 08:36:02

+0

實際上,如果一個人刪除行 matcher = keyPattern.matcher(str);來自while循環的 ,它應該工作,對吧? – 2010-01-11 10:05:34