实现说明
底层就是类 BoundedRegexLexer和函数 main。
使用要点
- 跑通全篇示例的唯一环境前提就是这门语言原生的开发工具链。
- 每一步打印都带着自己的标签:
key token:、opaque bounds match:、transparent bounds match:。
常见问题
运行「Matcher.usePattern 切模式与透明边界前瞻」会打印什么?
运行文件本身,key token:、opaque bounds match:、transparent bounds match: 这些前缀各对应一段演示逻辑。
主签名形如 public static void main(String[] args)
核心语句
Pattern keyPat = Pattern.compile("[a-z]+=");
代码示例
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() : ""));
}
}