2013-01-15 91 views
4

例如,我有以下正則表達式:\d{2}(2位數字)。當我使用Java匹配器。從一個序列返回幾個條目

Matcher matcher = Pattern.compile("\\d{2}").matcher("123"); 
    matcher.find(); 
    String result = matcher.group(); 

在結果變量我只得到第一個入口,即12。但我想獲得所有可能的條目,即1223

如何實現這一目標?

+0

調用'find()方法'在一個循環? –

回答

6

你需要一個積極的前瞻中的捕獲組的幫助:

Matcher m = Pattern.compile("(?=(\\d{2}))").matcher("1234"); 
while (m.find()) System.out.println(m.group(1)); 

打印

12 
23 
34 
+0

(+1)簡潔優雅的解決方案!看起來很棒。 – Alexandar

1

這不是正則表達式匹配的工作方式。匹配器從字符串的開始處開始,每當它找到匹配時,它就繼續從該匹配的結束後面的字符開始尋找 - 它不會給你重疊的匹配。

如果你想找到重疊的任意正則表達式匹配,無需使用通過重置匹配的「區域」向前看符號和捕獲組,你可以做到這一點每場比賽後

Matcher matcher = Pattern.compile(theRegex).matcher(str); 

// prevent^and $ from matching the beginning/end of the region when this is 
// smaller than the whole string 
matcher.useAnchoringBounds(false); 
// allow lookaheads/behinds to look outside the current region 
matcher.useTransparentBounds(true); 

while(matcher.find()) { 
    System.out.println(matcher.group()); 
    if(matcher.start() < str.length()) { 
    // start looking again from the character after the _start_ of the previous 
    // match, instead of the character following the _end_ of the match 
    matcher.region(matcher.start() + 1, str.length()); 
    } 
}