我不知道如何用简单的英语解释这个问题,所以我用regexp示例来帮助自己。我有类似的东西(这个例子非常简化):
((\\d+) - (\\d+)\n)+
此模式一次匹配这些行:
123 - 23
32 - 321
3 - 0
99 - 55
该模式包含3组:第一组匹配一条线,第二条匹配线中的第一个数字,第三条匹配线中的第二个数字。
是否有可能获得所有这些数字? Matcher只有3组。第一个返回99 - 55
,第二个返回99
,第三个返回55
。
SSCCE:
class Test {
private static final Pattern pattern = Pattern.compile("((\\d+) - (\\d+)\n)+");
public static void parseInput(String input) {
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
for (int i = 0; i <= matcher.groupCount(); i++) {
System.out.println("------------");
System.out.println("Group " + i + ": " + matcher.group(i));
}
System.out.println();
}
}
public static void main(String[] args) {
parseInput("123 - 23\n32 - 321\n3 - 0\n99 - 55\n");
}
}
答案 0 :(得分:8)
关于Mike Caron答案的另一个评论:如果您简单地用“while”替换“if”并使用“find”而不是“match”,程序将无效。您还应该更改正则表达式:应删除带有“+”的最后一个组,因为您要搜索此模式的多次出现,而不是一次出现(..)+组。
为清楚起见,这是最终的计划:
class Test {
private static final Pattern pattern = Pattern.compile("(\\d+) - (\\d+)\n");
public static void parseInput(String input) {
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
for (int i = 0; i <= matcher.groupCount(); i++) {
System.out.println("------------");
System.out.println("Group " + i + ": " + matcher.group(i));
}
System.out.println();
}
}
public static void main(String[] args) {
parseInput("123 - 23\n32 - 321\n3 - 0\n99 - 55\n");
}
}
每行将为您提供三个组,其中第一组是整行,后面两组包含一个数字。这是一个很好的教程,帮助我更好地理解它:http://tutorials.jenkov.com/java-regex/matcher.html
答案 1 :(得分:5)
如果我 错误(一种明显的可能性),那么每当你打电话给所以,基本上,将matcher.matches()
时,它都会在下一场比赛时更新。 if (matcher.matches())
更改为while (matcher.find())
,您就可以开始了。
编辑:实际上,它不是matches
,它是find
这样做:
http://download.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#find%28%29
以下是使用它的示例:
http://download.oracle.com/javase/tutorial/essential/regex/test_harness.html
答案 2 :(得分:2)
你是想分别匹配每一行吗?
删除+只匹配一行并更改:
if (matcher.matches()) {
为:
while (matcher.matches()) {
并且它将为每个匹配循环一次,并自动跳过匹配之间的任何不匹配的文本。
注意matcher.group(0)返回整个匹配。实际组以1开头。