Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex - overlapping matches

Tags:

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?

like image 495
Evgeny Avatar asked Jul 31 '13 13:07

Evgeny


1 Answers

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))); } 
like image 103
johnchen902 Avatar answered Oct 29 '22 21:10

johnchen902