How to get an "array group"?
Consider the following simplistic example:
+++++++++++++++++++++++++++++++++
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Test {
public static void main(String[] args) throws Exception
{
String text = "a, bb, ccc, dddd, eeeee, ffffff
and
gggggggggg";
String regex = "([^,]*)((, ([^,]*))* and
([^,]*))?";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
if (!matcher.matches())
throw new Exception("No match
found.");
for (int i = 0; i < matcher.groupCount()+1; i++)
System.out.println("Group " + i +
": " +
matcher.group(i));
}
}
+++++++++++++++++++++++++++++++++
I get the following result:
+++++++++++++++++++++++++++++++
Group 0: a, bb, ccc, dddd, eeeee, ffffff and gggggggggg
Group 1: a
Group 2: , bb, ccc, dddd, eeeee, ffffff and gggggggggg
Group 3: , ffffff
Group 4: ffffff
Group 5: gggggggggg
++++++++++++++++++++
That is:
group 1 contains the first element: a <-correct
group 5 contains the last element: ggggggg <- correct
However. I would need group 4 to contain an array with [bb,
ccc, dddd,
eeeee, fffffff] instead of just the last one (fffffff).
--------
This is what I mean by obtaining an "array
group".
How can I get this?
ps: I know that I could get that by recursively treating
group 2.
However, simply getting an "array group" for group
2 seems very
natural to me.
pss: maybe another regular expression package can do this?
The sample chapter of the O'Reilly book "Mastering
Regular
Expressions" is a comparison of several Java APIs
(however, it is a
little old): http://www.oreilly.com/catalog/regex2/chapter/ch08.pdf
Many thanks,
DAvid
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the
Google Groups "Regex" group.
To post to this group, send email to regex googlegroups.com
To unsubscribe from this group, send email to
regex-unsubscribe googlegroups.com
For more options, visit this group at http://groups.go
ogle.com/group/regex
-~----------~----~----~----~------~----~------~--~---
|