Following code gives exception on first run. But when I set break point on matcher line and evaluate a few commands in Netbeans Watcher. It works. Why??
String regex = "/I-TASSER/output/(?<jobId>.*?)>";
Pattern pattern;
Matcher matcher;
if (Pattern.compile(regex).matcher(document.html()).find()) {
pattern = Pattern.compile(regex);
matcher = pattern.matcher(document.html());
jobId = matcher.group("jobId"); //always give exception, so breakpoint here
}
I put following four lines in netbeans variable watcher
matcher.group("jobId"); //exception
matcher.find(); //true
matcher.group("jobId"); //S12345 /*found*/
Why it is?
You are re-assigning the Pattern and Matcher references within your if statement.
As such, you need to invoke matcher.find() again within that context to be able to invoke matcher.group(), otherwise it will throw an IllegalStateException - see API.
A much clearer and simpler syntax would be:
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(document.html());
if (matcher.find()) {
jobId = matcher.group("jobId");
}
Final advice, regex is not suitable for parsing html.
See the gazillion other posts about it.
The work for establishing groups happens in matches or find.
if (matcher.matches()) {
... matcher.group(...)
}
while (matcher.find()) {
... matcher.group(...)
}
With find there even is an iteration involved. And matches considers the entire text whereas find any subtext.
As it even is not clear what to do (matches or find) it does not even make sense to look what is found.
Twice compiling pattern and calling its matcher was probably an experiment, and can be cleaned up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With