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.
Code
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
Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.
FAQ
- How do you run Overlapping Matches With find(start)?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.