64 votes

"Aucune correspondance trouvée" lors de l'utilisation de la méthode de groupe de matcher

J'utilise Pattern / Matcher pour obtenir le code de réponse dans une réponse HTTP. groupCount renvoie 1, mais j'obtiens une exception en essayant de l'obtenir ! Une idée pourquoi ?

Voici le code :

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

Et voici la sortie :

 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)

105voto

Thomas Points 35713

pattern.matcher(input) crée toujours un nouveau matcher, vous devrez donc appeler à nouveau matches() .

Essayer:

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

12voto

Heiko Rupp Points 15153

Vous écrasez constamment les correspondances que vous avez obtenues en utilisant

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

Chaque ligne crée un nouvel objet Matcher.

Tu devrais y aller

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

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X