Java regex metal throw exception not found for match if pattern found in string

I'm dying trying to figure out why the regex won't match. Any help is much appreciated. I go along the line of the web page (this works great), but I need to pull out the links for each line. The application will check if there is a link in the line, but I need to actually pull out the url. to help?

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

The error message I get is the following:

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

Despite the fact that in the "result" there is a link to the link (hxxp: //www.yahoo.com).

References

is an ArrayList fyi. Thanks in advance!

+7
java regex matcher
source share
2 answers

Ok, so I figured it out. The only problem: my regex should have been

 ".*href=\"([^\"]*?)\".*" 

Who made the code

 private String regex = ".*href=\"([^\"]*?)\".*"; private Pattern p = Pattern.compile(regex); Matcher m = p.matcher(result); if (m.matches()) { String urlStr = m.group(1); links.add(urlStr); } 

So that was my regex problem, I had to use '?' so as not to be greedy, I think!

0
source share

first call

 m.find(); 

or

 m.matches(); 

and then you can use m.group() if the match is successful.

+9
source share

All Articles