java - index 和 offset 在 Java Regex 中有不同的含义?

标签 java regex api matcher

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

Matcher.start()

Matcher.end()

考虑以下代码:

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/

相关文章:

java - 在 ofEpochMilli 和 ofEpochSecond 之间切换

regex - 用减号替换空格,但仅限在括号内

java - 优化大量 Scanner.findWithinHorizo​​n(pattern, 0) 调用

regex - 用powershell中的控制字符Field Seperator(\034)替换一个字符

spring - 使用 RESTful 登录 API 验证我的 Spring Boot 应用程序

python - 使用Python中的请求迭代向API发送请求

api - CakePHP 3 REST API 身份验证,同时仍使用现有 Controller

java - 从迭代器转移到 for each

java - 验证 dto spring boot 中的三个字段中的至少一个

java - 当 File 类与平台无关时,为什么 File.isAbsolute() 与平台相关?