使用匹配器分组方法时“未找到匹配”

我使用 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)
63200 次浏览

pattern.matcher(input)总是创建一个新的匹配器,所以您需要再次调用 matches()

试试:

Matcher m = responseCodePattern.matcher(firstHeader);
m.matches();
m.groupCount();
m.group(0); //must call matches() first
...

你不断地覆盖你通过使用

System.out.println(responseCodePattern.matcher(firstHeader).matches());
System.out.println(responseCodePattern.matcher(firstHeader).groupCount());

每行创建一个新的 Matcher 对象。

你该走了

Matcher matcher = responseCodePattern.matcher(firstHeader);
System.out.println(matcher.matches());
System.out.println(matcher.groupCount());

或者你可以在 matcher.group(1)之前调用 matcher.find();

我也有同样的经历,但我写这个答案是因为我注意到了其他的东西:

正如其他人所说,你必须打电话

matcher.matches()

或者

matcher.find();

在你能打电话之前

matcher.group(1);

但是,如果使用 result ()调用,则不必显式调用上述方法,结果将立即可用。

pattern
.matcher(pathname)
.results()
.collect(Collectors.toList())
.get(0)
.group(1);

我认为这是故意的,但我只是在这里添加它

在使用 matcher.result () 时,不需要调用 matcher.find ()或 matcher.match ()。