Java Regex:为什么没有matcher.find(),matcher.group()不起作用?

时间:2014-09-15 15:13:04

标签: java regex

以下代码在首次运行时提供异常。但是当我在匹配器线上设置断点并评估Netbeans Watcher中的一些命令时。有用。为什么?

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
}

我在netbeans变量观察器中放了以下四行

matcher.group("jobId"); //exception
matcher.find();         //true
matcher.group("jobId"); //S12345 /*found*/

为什么会这样?

3 个答案:

答案 0 :(得分:6)

您正在Pattern声明中重新分配Matcherif个引用。

因此,您需要在该上下文中再次调用matcher.find()才能调用matcher.group(),否则会抛出IllegalStateException - 请参阅API

更清晰,更简单的语法是:

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(document.html());
if (matcher.find()) {
    jobId = matcher.group("jobId");
}

最后的建议,正则表达式不适合解析html。

查看关于它的大量其他帖子。

答案 1 :(得分:2)

建立群组的工作发生在matchesfind

if (matcher.matches()) {
    ... matcher.group(...)
}

while (matcher.find()) {
    ... matcher.group(...)
}

找到那里甚至涉及一个迭代。 matches考虑整个文本,而find考虑任何子文本。 因为它甚至不清楚该做什么(匹配或找到),看起来什么也没有意义。

两次编译模式并调用其匹配器可能是一个实验,可以清理。

答案 2 :(得分:1)

String regex = "/I-TASSER/output/(?<jobId>.*?)>";
String expression = document.html();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(expression);
while (matcher.find()) {
    String group = matcher.group();
}