gpt4 book ai didi

java - "No match Found"使用 matcher 的 group 方法时

转载 作者:IT老高 更新时间:2023-10-28 20:28:55 26 4
gpt4 key购买 nike

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

关于java - "No match Found"使用 matcher 的 group 方法时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5674268/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com