正则表达式捕获组中的组 [英] Regular expression capture groups which is in a group

查看:199
本文介绍了正则表达式捕获组中的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,如何获取组内的所有组(正则表达式)。

例如:使用(([AZ] [az] +)+)([0 -9] +)测试一个字符串:AbcDefGhi12345。

然后得到结果:

matches():yes

groupCount() :3

group(1):AbcDefGhi

group(2):Ghi

group(3):12345

In Java, how to get all groups which is inside a group (regular expression).
For example:Using (([A-Z][a-z]+)+)([0-9]+) test a string : "AbcDefGhi12345".
Then get Result:
matches():yes
groupCount():3
group(1):AbcDefGhi
group(2):Ghi
group(3):12345

但我想分别获得StringAbc,Def,Ghi,12345。

如何使用正则表达式来实现?

But I want to get String "Abc", "Def", "Ghi", "12345" respectively.
How can I do that by using regular expression?

推荐答案

正则表达式无法处理重复的组返回任何捕获的组(在您的情况下,它返回Ghi)。

Regular expressions cannot handle repeating groups it can return any of the captured groups (in your case it returned "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));
    }
}

这篇关于正则表达式捕获组中的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆