我不知道如何用简单的英语来解释这个问题,所以我用正则表达式来帮助自己。我有类似的东西(这个例子非常简单):
((\\d+) - (\\d+)\n)+
这个模式一次匹配这些行:
123 - 23
32 - 321
3 - 0
99 - 55
该模式包含 3 组:第一个匹配一行,第二个匹配行中的第一个数字,第三个匹配行中的第二个数字。
是否有可能获得所有这些数字?匹配器只有 3 个组。第一个返回 99 - 55
,第二个返回 99
,第三个返回 55
。
中南合作:
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");
}
}
最佳答案
关于 Mike Caron 的回答的更多评论:如果您简单地将“if”替换为“while”并使用“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
关于java - 如果多次匹配,有没有办法捕获每个组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4285013/