我对 start()
和 end()
定义中有关 Matcher 的 Java 文档感到有点困惑。
考虑以下代码:
public static void test()
{
String candidate = "stackoverflow";
Pattern p = Pattern.compile("s");
Matcher m = p.matcher(candidate);
m.find();
int index = m.start();
out.println("Index from Match\t"+index);
int offset = m.end();
out.println("Offset from match\t"+offset);
}
以上将返回以下结果。
Index from Match 0
Offset from match 1
据我了解,每个字符数组或字符串都将以索引 0 开始,并且它就在上面的表达式中。 但是 Offset 也返回相同的字符 's' 但为什么它以 1 开头?
最佳答案
不,它不是以 1 开头 - 它以 0 开头。文档相当清楚:
Returns the offset after the last character matched.
(强调我的。)
基本上是独占形式的匹配结束,这在Java中很常见。这意味着您可以执行以下操作:
String text = candidate.substring(matcher.start(), matcher.end());
请注意,您的“索引”和“偏移量”实际上应该被视为“开始”和“结束”(因此是方法名称)。在此上下文中,术语“索引”和“偏移量”实际上是同义词;重要的一点是 start()
返回匹配的 start 的索引/偏移量,而 end()
返回索引/偏移量在比赛结束之后。
关于java - index 和 offset 在 Java Regex 中有不同的含义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10471923/