我试图在字符串中查找 ^a{3} 模式,但不是从头开始。从位置2开始
例如:
Pattern pattern = Pattern.compile("^a{3}");
Matcher m = pattern.matcher("xxaaa");
System.out.println(m.find(2));
看来 ^ 表示字符串的开头(不是从位置 2 开始的字符串)
但是如何从位置 2 查找模式并确保 a{3} 从此位置开始
最佳答案
您可以将匹配器中的区域更改为从 2 开始,而无需弄乱原始正则表达式。见下文:
Pattern pattern = Pattern.compile("^a{3}");
Matcher m = pattern.matcher("xxaaa");
m.region(2, m.regionEnd()); // <---- region start is now 2
System.out.println(m.find());
System.out.println(m.lookingAt());
参见:https://docs.oracle.com/javase/9/docs/api/java/util/regex/Matcher.html#region-int-int-
关于带有 ^ 符号的 Java 正则表达式 : find from position,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48931853/