So, for an assignment I am trying to do some HTTP stuff. At the moment I am trying to extract the http status code from the response. This screamed regex to me, so I tried implementing it like so.
Pattern p = Pattern.compile("^HTTP\\/1\\.1 (\\d{3})");
Matcher m = p.matcher(response);
System.out.println(m.matches());
String code = m.group(0);
The response looks like this HTTP/1.1 200 OK…. When I try to run this, I get an IllegalStateException: No match found and matches() prints false. But if I copy the regex and the response text into an online regex evaluator (https://regexr.com/), it matches. Am I dumb? Shouldn’t this match? Is there a bug in the Java implementation? I suspect its the first one.
>Solution :
The matches method attempts to match the entire string against the pattern. Obviously, it won’t match, because of the OK at the end of the input. The Matcher method that you want to use is called find.
Read about the difference between matches and find in the Javadoc for Matcher