Carlos Roldán
Carlos Roldán

Reputation: 1091

How can I get overlapping RegEx matches in Java?

For example, using the pattern

[a-z]{2}

Over the string bcd, the only match will be [bc]. Instead, I'd like to get [bc, cd].

Upvotes: 3

Views: 139

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200158

You can get this with a lookahead that involves a capture group:

(?=([a-z]{2})).

You'll need a loop involving Matcher.find and query the matcher each time with group(1) to get your match. The main regex match itself is irrelevant and should be ignored.

Upvotes: 2

escitalopram
escitalopram

Reputation: 3856

Repeatedly use Matcher.find(int start) and Matcher.start() to find out, at which String index to look next.

String haystack="bcd";
Matcher m = pattern.matcher(haystack);
int lookIndex=0;
while(lookIndex < haystack.length() && m.find(lookIndex)) {
    lookIndex=m.start()+1;
    System.out.println("Found " + m.group());
}

Upvotes: 2

Related Questions