Java &引用;“未找到匹配项”;使用matcher';s群方法

Java &引用;“未找到匹配项”;使用matcher';s群方法,java,regex,http-headers,Java,Regex,Http Headers,我使用模式/匹配器在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(r

我使用
模式
/
匹配器
在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)
HTTP/1.1200正常
真的
1.
线程“thread-0”java.lang.IllegalStateException中的异常:未找到匹配项
位于java.util.regex.Matcher.group(未知源)
在cs236369.proxy.Response.(Response.java:27)
在cs236369.proxy.ProxyServer.start(ProxyServer.java:71)
在tests.Hw3Tests$1.run(Hw3Tests.java:29)
位于java.lang.Thread.run(未知源)
模式。匹配器(输入)总是创建一个新的匹配器,因此您需要再次调用
matches()

尝试:


您不断地覆盖通过使用

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());

上面是非常次优的代码。可以很容易地重写它以使用常量(
静态最终模式
),这样该模式只需编译一次。此外,重写非常容易,只需调用
Pattern.Matcher(String)
即可检索单个
Matcher
实例。在不使用
matches()
find()
的情况下调用
group()
时的错误不是很清楚,它应该只抛出一个
IllegalStateException
。@MaartenBodewes为什么在java中使用正则表达式如此冗长?这是问题的症结所在:Matcher有状态,所以OP是,正如您所说的,不断地覆盖它们。这是一个很容易犯的错误,你解释得很好。
Matcher matcher = responseCodePattern.matcher(firstHeader);
System.out.println(matcher.matches());
System.out.println(matcher.groupCount());