从字符串中,我需要拉出与给定模式匹配的组。
示例字符串:<XmlLrvs>FIRST</XmlLrvs><XmlLrvs>SECOND</XmlLrvs><XmlLrvs>Third</XmlLrvs>
每个小组应以<XmlLrvs>
开头,以</XmlLrvs>
结尾。这是我的代码片段......
String patternStr = "(<XmlLrvs>.+?</XmlLrvs>)+";
// Compile and use regular expression
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(text);
matcher.matches();
// Get all groups for this match
for (int i = 1; i<=matcher.groupCount(); i++) {
System.out.println(matcher.group(i));
}
输出为<XmlLrvs>Third</XmlLrvs>
。我期待第一组和第二组,但那些没有被捕获。有人可以帮忙吗?
答案 0 :(得分:8)
当您应该迭代匹配时,您正在迭代组。 matches()
方法检查整个输入是否匹配。你想要的是find()
方法。
更改
matcher.matches();
for (int i = 1; i<=matcher.groupCount(); i++) {
System.out.println(matcher.group(i));
}
到
while (matcher.find()) {
System.out.println(matcher.group(1));
}
答案 1 :(得分:0)
试一试
String patternStr = "<XmlLrvs>(.*?)</XmlLrvs>";
String text = "<XmlLrvs>FIRST</XmlLrvs><XmlLrvs>SECOND</XmlLrvs><XmlLrvs>Third</XmlLrvs>";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
The output is FIRST,SECOND,Third