Matcher UsePattern And TransparentBounds
Switch regex patterns mid-scan with Matcher.usePattern and enable useTransparentBounds so lookaheads inspect characters past regionEnd.
Code
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BoundedRegexLexer {
public static void main(String[] args) {
String input = "price=42USD;";
Pattern keyPat = Pattern.compile("[a-z]+=");
Pattern amountPat = Pattern.compile("\\d+(?=USD)");
Matcher matcher = keyPat.matcher(input);
if (matcher.lookingAt()) {
System.out.println("key token: " + matcher.group() + " end=" + matcher.end());
}
// Switch pattern and restrict region strictly to "42" [6, 8)
int valueStart = matcher.end();
matcher.usePattern(amountPat);
matcher.region(valueStart, valueStart + 2);
// Opaque bounds (default) hide "USD" beyond regionEnd, so lookahead (?=USD) fails
System.out.println("opaque bounds match: " + matcher.lookingAt());
// Transparent bounds let lookaheads inspect characters outside the region window
matcher.useTransparentBounds(true);
boolean matched = matcher.lookingAt();
System.out.println("transparent bounds match: " + matched + " value=" + (matched ? matcher.group() : ""));
}
}Walkthrough notes — Matcher UsePattern And TransparentBounds
Structurally, expect the class BoundedRegexLexer and the function main and nothing else.
Points of care
- Sole requirement for execution stays the stock language toolchain alone.
Applying it
Entry signature: public static void main(String[] args)
Emitted rows carry readable prefixes — key token:, opaque bounds match:, transparent bounds match: — when the file runs.
Statements that matter
Pattern keyPat = Pattern.compile("[a-z]+=");
Interactive Tools for This Topic
URL Pattern MatcherTest Express-style URL patterns with :param and wildcard segments against concrete paths and extract the captured parameter values.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.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.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
- What does Matcher UsePattern And TransparentBounds print when run?
- Execute the whole file; each printed line is prefixed with a label like `key token:`, `opaque bounds match:`, `transparent bounds match:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.