我对以下两者之间的区别感到有点困惑:
Matcher m;
m.group();和
Matcher m;
m.pattern().pattern();它们都从列表中返回正确的匹配项,但我不明白两者之间的区别。
发布于 2015-01-14 21:41:14
完全不同的东西。
Matcher.pattern().pattern()返回已根据输入初始化此Matcher的Pattern的String表示如果存在给定Pattern与给定文本的匹配,则返回主组匹配器(索引0)
如果没有找到匹配项,Matcher.group()将抛出IllegalStateException,即如果没有包装在matcher.find()布尔条件中。
Matcher.group(int i)重载允许您为您在Pattern中定义的显式组指定组索引(从1开始),按其出现的层次顺序(带括号)。
如果索引组没有在Pattern中定义,这些重载将抛出IndexOutOfBoundException。
示例
Pattern p = Pattern.compile(".+");
String input = "blah";
Matcher m = p.matcher(input);
if (m.find()) {
System.out.println(m.group());
System.out.println(m.pattern().pattern());
}输出
blah
.+More
here接口。
https://stackoverflow.com/questions/27944288
复制相似问题