Regular expression capture groups that are in a group

In Java, how to get all groups that are inside a group (regular expression).
For example: Using (([AZ] [az] +) +) ([0-9] +) check the line: "AbcDefGhi12345".
Then get the Result:
matches (): yes
groupCount (): 3
group (1): ABCDEFGHI
group (2): Ghi
group (3): 12345

But I want to get the lines "Abc", "Def", "Ghi", "12345" respectively.
How can I do this using regex?

+4
source share
3 answers

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

The following example will print:

 Abc Def Ghi 12345 

Code:

 public static void main(String[] args) { String example = "AbcDefGhi12345"; if (example.matches("(([AZ][az]+)+)([0-9]+)")) { Scanner s = new Scanner(example); String m; while ((m = s.findWithinHorizon("[AZ][az]+", 0)) != null) System.out.println(m); System.out.println(s.findWithinHorizon("[0-9]+", 0)); } } 
+1
source
 Pattern p = Pattern.compile("([AZ][az]+|(?:[0-9]+))"); Matcher m = p.matcher("AbcDefGhi12345"); while(m.find()){ System.out.println(m.group(1)); } 
+1
source

like an hzh answer with some format and a bit simpler:

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

gives you

 Abc Def Ghi 12345 
-1
source

Source: https://habr.com/ru/post/1333450/


All Articles