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):12345But 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
精彩评论