查看JDK中Matcher类的find、group方法的源码并给出注释
Matcher类的find()方法源码:
public boolean find() {
//重置lastMatch和lastAppendPosition为0
lastMatch = null;
if (first || !anchoringBounds) {
//如果是第一次查找或者没有边界限制,则需要重置查找范围为整个输入序列
if (input == null)
throw new IllegalStateException("No input found");
last = from;
first = false;
//将当前查找范围的end设置为输入序列的长度
oldLast = -1;
//判断是否需要重置region
if (hasAnchoringBounds())
reset(0, input.length());
}
//如果当前查找范围的起始位置大于等于输入序列的长度,则无法匹配,返回false
for (;;) {
//如果当前查找范围的起始位置大于等于输入序列的长度,则无法匹配,返回false
if (last > input.length()) {
// This is an erroneous state which should never occur
throw new IllegalStateException("Incorrect match");
}
//获取下一个匹配结果
MatchResult matchResult = matcher.match(this, last);
if (matchResult != null) {
//如果匹配成功,则更新lastMatch和lastAppendPosition,返回true
lastMatch = matchResult;
last = matchResult.end();
return true;
} else {
//如果匹配失败,则更新lastMatch和lastAppendPosition,返回false
last++;
if (isEnd(last))
break;
}
}
//如果没有匹配结果,则更新lastMatch和lastAppendPosition,返回false
lastMatch = null;
return false;
}
Matcher类的group()方法源码:
public String group() {
return group(0);
}
public String group(int group) {
if (first || lastMatch == null)
throw new IllegalStateException("No match available");
if (group < 0 || group > groupCount())
throw new IndexOutOfBoundsException("No group " + group);
if (lastMatch instanceof MatchResultImpl)
return ((MatchResultImpl)lastMatch).group(group);
if (group == 0)
return lastMatch.group();
return lastMatch.group(group);
}
注释:
- find()方法:该方法用于查找下一个匹配结果。首先,它会重置lastMatch和lastAppendPosition为0,并根据是否是第一次查找或者是否有边界限制来确定查找范围;然后,它会循环遍历查找范围,直到找到匹配结果或者无法匹配;最后,它会更新lastMatch和lastAppendPosition,并返回匹配结果是否成功的布尔值。
- group()方法:该方法用于获取匹配结果中指定组的子串。如果没有匹配结果或者指定的组不存在,则会抛出异常。如果匹配结果是MatchResultImpl类型,则直接调用它的group()或group(int)方法获取子串;否则,调用匹配结果的group()或group(int)方法获取子串
原文地址: https://www.cveoy.top/t/topic/cpt9 著作权归作者所有。请勿转载和采集!