Java写爬虫的时候,matcher.groupCount()返回为1,但是matcher.group(1)却抛异常

发布于 2022-09-04 00:13:32 字数 126 浏览 12 评论 0

图片描述

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷你仙 2022-09-11 00:13:32

我模仿了题意,写了测试代码,结果如下

String html = "<p><span>mytextvalue<br>";
Matcher m = Pattern.compile("<p><span>(.*?)<br>").matcher(html);
System.out.println(m.find()); //true
System.out.println(m.groupCount()); //1
System.out.println(m.group(0)); //<p><span>mytextvalue<br>
System.out.println(m.group(1)); //mytextvalue

另外

// where does m.groupCount come from
m = Pattern.compile("(group1)(group2)(group3)").matcher(html);
System.out.println(m.groupCount()); //3

增加解释说明,
看源码的注释

    /**
     * Returns the number of capturing groups in this matcher's pattern.
     *
     * <p> Group zero denotes the entire pattern by convention. It is not
     * included in this count.
     *
     * <p> Any non-negative integer smaller than or equal to the value
     * returned by this method is guaranteed to be a valid group index for
     * this matcher.  </p>
     *
     * @return The number of capturing groups in this matcher's pattern
     */
    public int groupCount() {
        return parentPattern.capturingGroupCount - 1;
    }

这里说得清楚,groupCount返回的是正则表达式的捕获分组的数量(捕获分组和非捕获分组是另外的知识点),groupCount的结果并不能说明匹配的结果。

要执行正则表达式匹配,需要执行find动作,看源码

    public boolean find() {
        int nextSearchIndex = last;
        if (nextSearchIndex == first)
            nextSearchIndex++;

        // If next search starts before region, start it at region
        if (nextSearchIndex < from)
            nextSearchIndex = from;

        // If next search starts beyond region then it fails
        if (nextSearchIndex > to) {
            for (int i = 0; i < groups.length; i++)
                groups[i] = -1;
            return false;
        }
        return search(nextSearchIndex);
    }

这样的才会给Matcher内部的成员变量groups赋值,groups[i] = -1;
这样的之后在我们执行m.group(1)的时候我们才能获得捕获分组匹配到的内容。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文