开发者

Regular expression capture groups which is in a group

开发者 https://www.devze.com 2023-02-01 01:56 出处:网络
In Java, how to get all groups which is i开发者_StackOverflow中文版nside a group (regular expression).

In Java, how to get all groups which is i开发者_StackOverflow中文版nside a group (regular expression).

For example:Using (([A-Z][a-z]+)+)([0-9]+) test a string : "AbcDefGhi12345".

Then get Result:

matches():yes

groupCount():3

group(1):AbcDefGhi

group(2):Ghi

group(3):12345

But I want to get String "Abc", "Def", "Ghi", "12345" respectively.

How can I do that by using regular expression?


Regular expressions cannot handle repeating groups it can return any of the captured groups (in your case it returned "Ghi").

The example below will print:

Abc
Def
Ghi
12345

The code:

public static void main(String[] args) {

    String example = "AbcDefGhi12345";

    if (example.matches("(([A-Z][a-z]+)+)([0-9]+)")) {

        Scanner s = new Scanner(example);

        String m;
        while ((m = s.findWithinHorizon("[A-Z][a-z]+", 0)) != null)
            System.out.println(m);

        System.out.println(s.findWithinHorizon("[0-9]+", 0));
    }
}


Pattern p = Pattern.compile("([A-Z][a-z]+|(?:[0-9]+))");
Matcher m = p.matcher("AbcDefGhi12345");
while(m.find()){
   System.out.println(m.group(1));
}


like hzh's answer with some format and a little bit simpler:

Pattern p = Pattern.compile("[A-Z][a-z]+|[0-9]+"); 
Matcher m = p.matcher("AbcDefGhi12345"); 
while(m.find()){ 
    System.out.println(m.group(0)); 
}

gives you

Abc
Def
Ghi
12345
0

精彩评论

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

关注公众号