我正在使用
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)
pattern.matcher(input)
总是创建一个新的匹配器,因此您需要再次调用 matches()
。
尝试:
Matcher m = responseCodePattern.matcher(firstHeader);
m.matches();
m.groupCount();
m.group(0); //must call matches() first
...
您不断地覆盖通过使用获得的匹配项
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());
我也经历过同样的事情,但我写这个答案是因为我注意到了其他事情:
正如其他人所说,你必须打电话
matcher.matches()
或
matcher.find();
打电话之前
matcher.group(1);
但是,如果您使用 results() 调用,则 不需要明确调用上面的这些方法,并且结果立即可用。
pattern
.matcher(pathname)
.results()
.collect(Collectors.toList())
.get(0)
.group(1);
我认为这是故意的,但我只是在这里添加它
使用matcher.results()时无需调用matcher.find()或matcher.matches()。
或者您可以在
matcher.find();
之前致电
matcher.group(1)