Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
索引和偏移在Java正则表达式中有不同的含义?_Java_Regex_Api_Matcher - Fatal编程技术网

索引和偏移在Java正则表达式中有不同的含义?

索引和偏移在Java正则表达式中有不同的含义?,java,regex,api,matcher,Java,Regex,Api,Matcher,在start()和end()的定义中,我对Java文档中关于Matcher的内容感到有点困惑 考虑以下代码: public static void test() { String candidate = "stackoverflow"; Pattern p = Pattern.compile("s"); Matcher m = p.matcher(candidate); m.find(); int in

start()
end()
的定义中,我对Java文档中关于Matcher的内容感到有点困惑

考虑以下代码:

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);
}
上述操作将返回以下结果

来自匹配0的索引

与比赛1的偏移量

正如我所了解到的,每个字符数组或字符串都将以索引0开始,它就在上面的表达式中。
但是偏移量也返回相同的字符“s”,但为什么它以1开头?

不,它不是以1开头的,而是以0开头的。文件清楚地表明:

返回匹配的最后一个字符后的偏移量

(我的重点。)

基本上,它以排他形式结束了比赛,这在Java中很常见。这意味着你可以做如下事情:

String text = candidate.substring(matcher.start(), matcher.end());

请注意,您的“索引”和“偏移量”实际上应该被视为“开始”和“结束”(因此方法名)。术语“索引”和“偏移量”在此上下文中实际上是同义词;重要的一点是,
start()
返回匹配开始时的索引/偏移量,
end()
返回匹配结束后的索引/偏移量。

“返回匹配最后一个字符后的偏移量”?这不是索引偏移量语义。两者都是指数,一个是起始位置,另一个是结束位置。就像在
String.substring中一样