Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 592
johwiltb Avatar asked Mar 25 '14 11:03

johwiltb


People also ask

What does \\ mean in Java regex?

Backslashes in Java. The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.

What is PatternSyntaxException?

A PatternSyntaxException is an unchecked exception that indicates a syntax error in a regular expression pattern. The PatternSyntaxException class provides the following methods to help you determine what went wrong: public String getDescription() : Retrieves the description of the error.

What is PatternSyntaxException java?

The java. util. regex. PatternSyntaxException class represents a unchecked exception thrown to indicate a syntax error in a regular-expression pattern.

What does pattern matcher do?

The matcher() method is used to search for the pattern in a string. It returns a Matcher object which contains information about the search that was performed. The find() method returns true if the pattern was found in the string and false if it was not found.


1 Answers

first call

m.find();

or

m.matches();

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

like image 185
Sergey Fedorov Avatar answered Oct 19 '22 01:10

Sergey Fedorov