Java regular expression matcher mismatch

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);

Get error:

java.lang.IllegalStateException: No match found

Test my regular expression here and it matches:

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

Solution

You need to do this first

matcher.find()

Trigger actual search This is usually the case:

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

You might want to use a different regular expression:

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

It will be safer and more effective (and provide the correct value in Group No. 1)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>