Evgeny Evgeny - 3 years ago 165
Java Question

Java regex - overlapping matches

In the following code:

public static void main(String[] args) {
List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile("\\d+\\D+\\d+").matcher("2abc3abc4abc5");
while (m.find()) {
allMatches.add(m.group());
}

String[] res = allMatches.toArray(new String[0]);
System.out.println(Arrays.toString(res));
}


The result is:

[2abc3, 4abc5]


I'd like it to be

[2abc3, 3abc4, 4abc5]


How can it be achieved?

Answer Source

Make the matcher attempt to start its next scan from the latter \d+.

Matcher m = Pattern.compile("\\d+\\D+(\\d+)").matcher("2abc3abc4abc5");
if (m.find()) {
    do {
        allMatches.add(m.group());
    } while (m.find(m.start(1)));
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download