当前位置: 首页 > 面试题库 >

使用匹配器的分组方法时,“找不到匹配项”

孟海
2023-03-14
问题内容

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


 类似资料:
  • null 我正在CentOS Linux版本7.3.1611的虚拟环境中使用Python2.7。 我正在运行一个使用matplotlib.pyplot的脚本,运行时会出现以下错误 我试着用- 然后我甚至安装了- 并且它表示包已经安装并且 我已经重新设置了我的虚拟环境,看看我是否错过了什么,但我无法到达任何地方。请救命!

  • 以下代码: 编译期间生成以下错误: List namesAsList=names.collect(()->new ArrayList(),List::Add,List::Add);^(参数不匹配;无效的方法引用不兼容的类型:ArrayList无法转换为int)其中R,T是类型变量:R在方法collect中声明的extends Object(Supplier,BiConsumer,BiConsume

  • 我在angular 5中实现了一个模式,在.ts文件中使用以下代码进行密码验证。这样做的目的是支持至少八个字符,至少一个大写字母、一个小写字母、一位数字和一个特殊字符。请参阅:密码的Regex必须包含至少八个字符、至少一个数字以及大小写字母和特殊字符 我明白了,当我在密码文本框中输入一个字符串时,例如< code>Niladri1!然而,当我输入一个类似于< code>Nopasss123!!,它

  • 当运行此操作时,可以看到批处理仍被打印为。我在设置交互时做错了什么?

  • 问题内容: 当我测试此静态方法时 与 我知道了。我的问题是: 当所有参数都使用匹配器时,为什么会出现此异常?怎么解决呢?我已经调试了它,发现返回null。 当我将注释添加到测试类并运行测试时,junit不会响应。为什么? 编辑 我试图不使用参数匹配器,并得到 org.mockito.exceptions.misusing.MissingMethodInvocationException:when(

  • 我可以使用哪种匹配器? { test: /\.js$/, loader: 'babel-loader' } - Matches just .js { test: /\.(js|jsx)$/, loader: 'babel-loader' } - Matches both js and jsx Generally put it's just a JavaScript regex so standar