代码之家  ›  专栏  ›  技术社区  ›  Kalle Richter

用于记录消息的Java正则表达式[重复]

  •  0
  • Kalle Richter  · 技术社区  · 8 年前

    我在用 Pattern / Matcher 获取HTTP响应中的响应代码。 groupCount 返回1,但我在尝试获取时遇到异常!知道为什么吗?

    以下是代码:

    //get response code
    String firstHeader = reader.readLine();
    Pattern responseCodePattern = Pattern.compile("^HTTP/1\\.1 (\\d+) OK$");
    System.out.println(firstHeader);
    System.out.println(responseCodePattern.matcher(firstHeader).matches());
    System.out.println(responseCodePattern.matcher(firstHeader).groupCount());
    System.out.println(responseCodePattern.matcher(firstHeader).group(0));
    System.out.println(responseCodePattern.matcher(firstHeader).group(1));
    responseCode = Integer.parseInt(responseCodePattern.matcher(firstHeader).group(1));
    

    以下是输出:

    HTTP/1.1 200 OK
    true
    1
    Exception in thread "Thread-0" java.lang.IllegalStateException: No match found
     at java.util.regex.Matcher.group(Unknown Source)
     at cs236369.proxy.Response.<init>(Response.java:27)
     at cs236369.proxy.ProxyServer.start(ProxyServer.java:71)
     at tests.Hw3Tests$1.run(Hw3Tests.java:29)
     at java.lang.Thread.run(Unknown Source)
    
    0 回复  |  直到 8 年前
        1
  •  117
  •   Thomas    15 年前

    pattern.matcher(input) 总是创建一个新的匹配器,所以你需要打电话 matches() 再一次

    尝试:

    Matcher m = responseCodePattern.matcher(firstHeader);
    m.matches();
    m.groupCount();
    m.group(0); //must call matches() first
    ...
    
        2
  •  14
  •   Heiko Rupp    15 年前

    你不断地覆盖通过使用

    System.out.println(responseCodePattern.matcher(firstHeader).matches());
    System.out.println(responseCodePattern.matcher(firstHeader).groupCount());
    

    每行创建一个新的匹配器对象。

    你该走了

    Matcher matcher = responseCodePattern.matcher(firstHeader);
    System.out.println(matcher.matches());
    System.out.println(matcher.groupCount());
    
        3
  •  1
  •   hatanooh    4 年前

    或者你可以打电话 matcher.find(); 之前 matcher.group(1)

        4
  •  1
  •   Marian Klühspies    4 年前

    我也经历过同样的经历,但我写这个答案是因为我注意到了其他一些东西:

    正如其他人所说,你必须打电话

    matcher.matches()
    

    或

    matcher.find();
    

    在你打电话之前

    matcher.group(1);
    

    但是,如果使用results()调用,则不必显式调用上述方法,结果立即可用。

    pattern
            .matcher(pathname)
            .results()
            .collect(Collectors.toList())
            .get(0)
            .group(1);
    

    我认为这是故意的,但我只是在这里补充一下

    不用打电话给matcher。查找()或匹配器。使用matcher时匹配()。结果() .