quot;No match Foundquot; when using matcher#39;s group method(“未找到匹配项使用 matcher 的 group 方法时)
问题描述
我正在使用 Pattern
/Matcher
来获取 HTTP 响应中的响应代码.groupCount
返回 1,但尝试获取时出现异常!知道为什么吗?
I'm using Pattern
/Matcher
to get the response code in an HTTP response. groupCount
returns 1, but I get an exception when trying to get it! Any idea why?
代码如下:
//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()
再次.
pattern.matcher(input)
always creates a new matcher, so you'd need to call matches()
again.
试试:
Matcher m = responseCodePattern.matcher(firstHeader);
m.matches();
m.groupCount();
m.group(0); //must call matches() first
...
这篇关于“未找到匹配项"使用 matcher 的 group 方法时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“未找到匹配项"使用 matcher 的 group 方法时


- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01