java regex matching each group starting with specific string
java, regex
Solution
Split is a good solution, but if you want to remain in the regex world, here is a solution:
Matcher m = Pattern.compile("(a1.*?)(?=a1|$)").matcher("a1wwa1xxa1yya1zz");
while (m.find()) {
String myGroup = m.group(1);
System.out.println("> " + myGroup);
}
I used a positive lookahead to ensure the capture is followed by `a1`, or alternatively by the end of line.
Lookahead are zero-width assertions, ie. they verify a condition without advancing the match cursor, so the string they verify remains available for further testing.
Problem
I have a string like `a1wwa1xxa1yya1zz`. I would like to get every groups starting with a1 until next a1 excluded. (In my example, i would be : `a1ww`, `a1xx`, `a1yy`and `a1zz` If I use : ``` Matcher m = Pattern.compile("(a1.*?)a1").matcher("a1wwa1xxa1yya1zz"); while(m.find()) { String myGroup = m.group(1); } ``` `myGroup` capture 1 group every two groups. So in my example, I can only capture `a1ww` and `a1yy`. Anyone have a great idea ?