In .NET, if I want to match a sequence of characters against a pattern that describes capturing groups that occur any number of times, I could write something as follows:
String input = "a, bc, def, hijk";
String pattern = "(?<x>[^,]*)(,\\s*(?<y>[^,]*))*";
Match m = Regex.Match(input, pattern);
Console.WriteLine(m.Groups["x"].Value);
//the group "y" occurs 0 or more times per match
foreach (Capture c in m.Groups["y"].Captures)
{
Console.WriteLine(c.Value);
}
This code would print:
a
bc
def
hijk
That seems straightforward, but unfortunately the following Java code doesn't do what the .NET code does. (Which is expected, since java.util.regex doesn't seem to distinguish between groups and captures.)
String input = "a, bc, def, hijk";
Pattern pattern = Pattern.compile("(?<x>[^,]*)(,\\s*(?<y>[^,]*))*");
Matcher m = pattern.matcher(input);
while(m.find())
{
System.out.println(m.group("x"));
System.out.println(m.group("y"));
}
Prints:
a
hijk
null
Can someone please explain how to accomplish the same using Java, without having to re-write the regular expression or use external libraries?