Ami*_*hum 54 java regex http-headers
我正在使用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));
Run Code Online (Sandbox Code Playgroud)
这是输出:
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)
Run Code Online (Sandbox Code Playgroud)
Tho*_*mas 90
pattern.matcher(input)总是创建一个新的匹配器,所以你需要matches()再次打电话.
尝试:
Matcher m = responseCodePattern.matcher(firstHeader);
m.matches();
m.groupCount();
m.group(0); //must call matches() first
...
Run Code Online (Sandbox Code Playgroud)
Hei*_*upp 11
你不断覆盖你使用的比赛
System.out.println(responseCodePattern.matcher(firstHeader).matches());
System.out.println(responseCodePattern.matcher(firstHeader).groupCount());
Run Code Online (Sandbox Code Playgroud)
每行创建一个新的Matcher对象.
你该走了
Matcher matcher = responseCodePattern.matcher(firstHeader);
System.out.println(matcher.matches());
System.out.println(matcher.groupCount());
Run Code Online (Sandbox Code Playgroud)
我也经历过同样的事情,但我写这个答案是因为我注意到了其他事情:
正如其他人所说,你必须致电
matcher.matches()
Run Code Online (Sandbox Code Playgroud)
或者
matcher.find();
Run Code Online (Sandbox Code Playgroud)
在您可以打电话之前
matcher.group(1);
Run Code Online (Sandbox Code Playgroud)
但是,如果您使用results()调用,则不必明确调用上面的这些方法,并且结果立即可用。
pattern
.matcher(pathname)
.results()
.collect(Collectors.toList())
.get(0)
.group(1);
Run Code Online (Sandbox Code Playgroud)
我认为这是故意的,但我只是在这里添加它
使用 matcher.results() 时无需调用 matcher.find() 或 matcher.matches()。