Matcher Region Bounds The Search
Constrain regex scanning to a slice of a large payload with Matcher.region, so hits outside [regionStart, regionEnd) are never reported.
Code
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionScan {
public static void main(String[] args) {
Pattern id = Pattern.compile("ORD-\\d{4}");
String payload = "ORD-0001 ignored ORD-0002 kept ORD-0003";
// 只扫描 [start, end) 区间:区间外的命中一律视而不见
int start = payload.indexOf("ORD-0002");
Matcher m = id.matcher(payload);
m.region(start, payload.length());
int hits = 0;
while (m.find()) {
hits++;
System.out.println(m.group() + " in [" + m.regionStart() + "," + m.regionEnd() + ")");
}
System.out.println("hits inside region: " + hits);
}
}Bounded scanning
m.region(start, payload.length()) confines all subsequent find() calls to that half-open range; hits before regionStart are never reported. The demo picks start as the index of ORD-0002, so the two hits printed are ORD-0002 and ORD-0003 — ORD-0001 is outside the region.
Visible bounds
Each hit line embeds m.regionStart() and m.regionEnd(), so the output shows the scan window it operated in, and hits inside region: 2 confirms the count.
Where this applies
Large payloads (logs, payloads with header sections) often only warrant scanning a slice; region() avoids substring copies while giving the same effect.
Interactive Tools for This Topic
FAQ
- Why use region() instead of substring()?
- region() constrains the Matcher without copying characters; substring() allocates a new string of the sliced range before matching.
- What does the demo print for hits?
- Two hits inside the region — ORD-0002 and ORD-0003 — each with the region bounds, and a final count of 2.
Report a problem with this exampleOpens a pre-filled issue on GitHub.