Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am trying to evaluate a regex, but it doesn't match, although it should

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading