使用匹配器的组方法时“找不到匹配项”

新手上路,请多包涵

我正在使用 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)

原文由 Amir Rachum 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 490
2 个回答

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

尝试:

 Matcher m = responseCodePattern.matcher(firstHeader);
m.matches();
m.groupCount();
m.group(0); //must call matches() first
...

原文由 Thomas 发布,翻译遵循 CC BY-SA 3.0 许可协议

您不断地覆盖通过使用获得的匹配项

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

每行创建一个新的 Matcher 对象。

你该走了

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

原文由 Heiko Rupp 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题