"Nie znaleziono dopasowania" przy użyciu metody grupy matchera

Używam Pattern/Matcher aby uzyskać kod odpowiedzi w odpowiedzi HTTP. groupCount zwraca 1, ale dostaję wyjątek, gdy próbuję go zdobyć! Wiesz dlaczego?

Oto kod:

//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));

A oto wyjście:

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)
Author: Karl Richter, 2011-04-15

2 answers

pattern.matcher(input) zawsze tworzy nowy matcher, więc musisz zadzwonić matches() ponownie.

Try:

Matcher m = responseCodePattern.matcher(firstHeader);
m.matches();
m.groupCount();
m.group(0); //must call matches() first
...
 104
Author: Thomas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-15 11:06:58

Ciągle nadpisujesz dopasowania, które otrzymałeś za pomocą

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

Każda linia tworzy nowy obiekt Matcher.

Powinieneś iść

Matcher matcher = responseCodePattern.matcher(firstHeader);
System.out.println(matcher.matches());
System.out.println(matcher.groupCount());
 12
Author: Heiko Rupp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-15 08:51:01