Java regex throwing exception for no match found when pattern found in line

johwiltb picture johwiltb · Mar 25, 2014 · Viewed 14.6k times · Source

I am dying trying to figure out why a regex won't match. Any help is much appreciated. I'm going line by line of a web page (that works fine), but I need to pull out the links for each line. The application will check to see if there is a link in the line, but I need to actually pull out the URL. help?

Pattern p = Pattern.compile("^.*href=\"([^\"]*)");
Matcher m = p.matcher(result);
String urlStr = m.group();
links.add(urlStr);

The error message I keep getting is this:

Exception in thread "main" java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Matcher.java:485)

Even though 'result' has a link reference (hxxp://www.yahoo.com) in it.

links is an ArrayList fyi. Thanks in advance!

Answer

Sergey Fedorov picture Sergey Fedorov · Mar 25, 2014

first call

m.find();

or

m.matches();

and then you'll be able to use m.group() if matcher succeeded.