开发者

Capturing all numbers from string with regular expressions without splitting

I need to use some regular expressions to parse more complicated text and I wonder whether it is possible to use non capturing groups to match multiple numbers and extract them? I und开发者_如何学JAVAerstand that I can match white-space separated numbers and then split them by white-spaces but I would like to get all numbers in different groups even though I don't know their quantity.

Example below matches only last number:

----Start----
--------
i 0 11 22 4444 
i 1 4444
--------
i 0 34 56
i 1 56

But i would like to get:

----Start----
--------
i 0 11 22 4444 
i 1 11
i 2 22
i 3 4444
--------
i 0 34 56
i 1 34
i 2 56

Here goes my code:

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

public class Main{
    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("----Start----");

        Pattern compile = Pattern.compile("(?:(\\d+)\\s*)+");
        String s = "11 22 4444 mam a 34 56";

        Matcher matcher = compile.matcher(s);
        while(matcher.find()){
            System.out.println("--------");
            for (int i=0;i<matcher.groupCount()+1;i++){
                System.out.println("i " + i = " " + matcher.group(i));
            }
        }
    }
}


You can't do that, so split the match. Only the last value of the capturing group is stored. As far as I know only .NET regex saves all the previous captures.


    matcher = compile.matcher(s);
    Pattern subCompile = Pattern.compile("(\\d+)");
    while (matcher.find()) {
        System.out.println("--------");
        Matcher subMatcher = subCompile.matcher(matcher.group());
        while (subMatcher.find())
            System.out.println(subMatcher.group());
    }

also works. Output:

--------
11
22
4444
--------
34
56
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜