3

My String:

<a href="https://MYURL/browse/TEST-53">FOO.BAR</a></p>

Code:

Pattern pattern = Pattern.compile("(browse/)(.*)(\">)");
Matcher matcher = pattern.matcher(match);

return matcher.group(1);

Getting error:

java.lang.IllegalStateException: No match found

Tested my regex here, it does match:

http://regexpal.com/?flags=g&regex=(browse%2F)(.*)(%5C%22%3E)&input=%3Ca%20href%3D%22https%3A%2F%2FMYURL%2Fbrowse%2FTEST-53%22%3EFOO.BAR%3C%2Fa%3E%3C%2Fp%3E

3 Answers 3

13

You first need to do

matcher.find()

to trigger the actual search. Usually like this:

Pattern pattern = Pattern.compile("(browse/)(.*)(\">)");
Matcher matcher = pattern.matcher(match);
if (matcher.find()) 
    return matcher.group(1);

You should probably be using a different regex, though:

Pattern pattern = Pattern.compile("browse/([^<>\"]*)\">");

will be safer and more efficient (and provide the correct value in group number 1).

Sign up to request clarification or add additional context in comments.

Comments

5

You have to call Matcher.find() or Matcher.matches() before you extract groups.

In your exact case you should call Matcher.find(), since your regex won't match against the entire input, which is what Matcher.matches() checks for.

Comments

0

If you using Java > 7. You can define group Name:

String TEXT = "<a href=\"https://MYURL/browse/TEST-53\">FOO.BAR</a></p>"
        +"<a href=\"https://MYURL/browse/TEST2\">FOO2.BAR</a></p>" ;

// Define group named value  (?<groupName>regexHere)
// *?  ==>  ? after a quantifier makes it a reluctant quantifier. 
// It tries to find the smallest match.
String regex = "browse/(?<value>.*?)\">";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(TEXT);

while (matcher.find()) {
    // Get group by name.
    System.out.println("Value = " + matcher.group("value"));
}

Result:

Value = TEST-53
Value = TEST2

MORE for Group Name Tutorial.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.