代码之家  ›  专栏  ›  技术社区  ›  Dogemore

System.out.print删除匹配器类异常

  •  1
  • Dogemore  · 技术社区  · 7 年前

    所以我用Jsoup来抓取一些网页,这个有线问题就发生了。

    // Sets the prefix for all pages to prevent navigate to unwanted pages.
    String prefix = "https://handbook.unimelb.edu.au/%d/subjects";
    // Postfix for search page
    String searchPostfix = "(\\?page=\\d+)?$";
    // Postfix for subject page
    String subjectPostfix = "\\/(\\w+)(\\/.+)?$";
    
    String root = String.format(prefix, "2019");
    String pattern = root.replace("/", "\\/").replace(".", "\\.");
    Pattern reg1 = Pattern.compile("^" + pattern + searchPostfix);
    Pattern reg2 = Pattern.compile("^" + pattern + subjectPostfix);
    

    使用这些正则表达式模式。我用绳子拉它

    String s1 = "https://handbook.unimelb.edu.au/2019/subjects/undergraduate";
    

    用一种方法:

    private String getSubjectCode(String link) {
        System.out.println(link);
        if (isSubjectPage(link)) {
            Matcher subjectMatcher = subjectPattern.matcher(link);
            System.out.println(link);
            // System.out.println(subjectMatcher.matches());   ## Exception if commented
            System.out.println(subjectMatcher.group(0));
            System.out.println(subjectMatcher.group(1));
    
    
            return subjectMatcher.group(1);
        }
        return null;
    }
    

    但是,如果我评论这句话

    Exception in thread "main" java.lang.IllegalStateException: No match found
        at java.base/java.util.regex.Matcher.group(Matcher.java:645)
        at Page.Pages.getSubjectCode(Pages.java:54)
        at Page.Pages.enqueue(Pages.java:85)
        at Crawler.Crawler.parsePage(Crawler.java:41)
        at Crawler.Crawler.crawl(Crawler.java:51)
        at Main.main(Main.java:9)
    

    将引发上述异常,为什么打印行会影响程序的运行?

    而且,没有任何评论

    System.out.println(subjectMatcher.matches());   // Exception if commented
    // out -> true
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Community Mohan Dere    6 年前

    事实并非如此 System.out.println 这导致了差异,但是调用该方法会产生副作用 matches() .

    这一点在本手册中有解释 JavaDocs of Matcher

    匹配器是通过调用模式的匹配器方法从模式中创建的。一旦创建,匹配器可用于执行三种不同类型的匹配操作:

    • matches 方法尝试根据模式匹配整个输入序列。
    • lookingAt 方法尝试根据模式匹配输入序列,从开头开始。
    • find 方法扫描输入序列,查找与模式匹配的下一个子序列。

    IllegalStateException 被扔掉。匹配器的显式状态由每个匹配操作重新计算。

    你要么打电话 , 寻找 然后才能执行进一步的查询,例如 group(0) .