Overlapping Matches With find(start)

find() resumes at the previous match end, so overlapping hits are invisible; restarting find from start+1 reveals every occurrence.

JavaCli Tooling

Code

snippet
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OverlapScan {

    // find() 默认从上次匹配的 end 继续:相邻匹配会互相"吃掉"位置
    static List<Integer> overlaps(String text, String regex) {
        Pattern pattern = Pattern.compile(regex);
        List<Integer> hits = new ArrayList<>();
        Matcher matcher = pattern.matcher(text);
        int from = 0;
        while (matcher.find(from)) {
            hits.add(matcher.start());
            from = matcher.start() + 1; // 只前进一位,允许匹配重叠
        }
        return hits;
    }

    public static void main(String[] args) {
        System.out.println(overlaps("aaaa", "aa"));    // [0, 1, 2],普通 find() 只报 2 处
        System.out.println(overlaps("banana", "ana")); // [1, 3],普通 find() 只报 1 处
    }
}

Walking the logic

The snippet is organized around the class OverlapScan and the functions overlaps and main.

The cycling part of this snippet is while (matcher.find(from)).

What to watch for

  • Any import in the file resolves to a standard-library module.

Applying it

Entry signature: static List<Integer> overlaps(String text, String regex)

Launch the file; main takes over and steps through overlaps.

Statements that matter

from = matcher.start() + 1; // 只前进一位,允许匹配重叠
}
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);

Interactive Tools for This Topic

FAQ

How do you run Overlapping Matches With find(start)?
Nothing to install first — run the file and the program does the rest.