我不知道如何用简单的英语解释这个问题,所以我用regexp例子来帮助自己.我有类似的东西(这个例子非常简化):
((\\d+) - (\\d+)\n)+
Run Code Online (Sandbox Code Playgroud)
此模式一次匹配这些行:
123 - 23
32 - 321
3 - 0
99 - 55
Run Code Online (Sandbox Code Playgroud)
该模式包含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");
}
}
Run Code Online (Sandbox Code Playgroud)
mar*_*oid 10
关于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");
}
}
Run Code Online (Sandbox Code Playgroud)
它将为每行提供三个组,其中第一组是整行,后面两组包含一个数字.这是一个很好的教程,帮助我更好地理解它:http://tutorials.jenkov.com/java-regex/matcher.html
如果我没有弄错(一个明显的可能性),那么每次你打电话所以,基本上,matcher.matches()
,它都会在下一场比赛中更新.if (matcher.matches())
改成a 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