在 Java 中,如何获取组内的所有组(正则表达式)。
例如:使用 (([A-Z][a-z]+)+)([0-9]+) 测试字符串:“AbcDefGhi12345”。
然后得到结果:
匹配():是的
groupCount():3
组(1):AbcDefGhi
组(2):Ghi
组(3):12345
但是我想分别得到String "Abc", "Def", "Ghi", "12345"。
我如何使用正则表达式来做到这一点?
最佳答案
正则表达式无法处理重复组,它可以返回任何捕获的组(在您的情况下它返回 "Ghi"
)。
下面的例子将打印:
Abc
Def
Ghi
12345
代码:
public static void main(String[] args) {
String example = "AbcDefGhi12345";
if (example.matches("(([A-Z][a-z]+)+)([0-9]+)")) {
Scanner s = new Scanner(example);
String m;
while ((m = s.findWithinHorizon("[A-Z][a-z]+", 0)) != null)
System.out.println(m);
System.out.println(s.findWithinHorizon("[0-9]+", 0));
}
}
关于java - 正则表达式捕获组在一个组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4537191/