1

I have a Java regular expression group that can appear 0 or more times, but I am not sure how to reference matches if they occur multiple times.

Simplified example:

Pattern myPattern = Pattern.compile("(?<myGroupName>foo.)*"); // notice greoup "myGroupName" can appear 0 or more times
Matcher myMatcher = myPattern.matcher("foo1foo2foo3"); // notice the named group "myGroupName" appears 3 times
myMatcher.find(); 
myMatcher.group("myGroupName"); // This will return "foo3".. foo1 and foo2 are lost

Update:

Thanks for the help aioobe! Unfortunately I need reference these matches by name to differentiate groups and handle the corresponding data appropriately. I got around this by moving the "*" (0 or more character) inside the group and iterating over the match with a second regular expression:

        String regex = "foo.x";
    Pattern myPattern = Pattern.compile("(?<myGroupName>(" + regex + ")*)"); // notice greoup "myGroupName" can appear 0 or more times
    Pattern specPattern = Pattern.compile(regex);

    Matcher myMatcher = myPattern.matcher("foo1xfoo2xfoo3x"); // notice the named group "myGroupName" appears 3 times
    myMatcher.find();
    System.out.println(myMatcher.group("myGroupName"));
    Matcher specMatcher = specPattern.matcher(myMatcher.group("myGroupName"));

    while(specMatcher.find()){
        System.out.println(specMatcher.group());
    }
Ninja John
  • 35
  • 7

1 Answers1

2

You can't. The group will contain the last match. (There's a static number of groups, and the last match overrides any previous match.)

You will have to rewrite your logic and use a loop to repeatedly find() the next match.

Related question (maybe even a duplicate): Regular expression with variable number of groups?

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826