如何解决使用匹配器的分组方法时,“找不到匹配项”
pattern.matcher(input)
总是会创建一个新的匹配器,因此您需要matches()
再次致电。
尝试:
Matcher m = responseCodePattern.matcher(firstHeader);
m.matches();
m.groupCount();
m.group(0); //must call matches() first
...
解决方法
我正在使用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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。