来源:互联网 发布:易燃物品附有的数据 编辑:程序博客网 时间:2024/04/29 11:40

组是由圆括号分开的正则表达式,随后可以根据它们的组号进行调用。第 0 组表示整个匹

配表达式,第1 组表示第 1 个用圆括号括起来的组,等等。因此,在表达式

 

A(B(C))D

 

中,有 3 个组:第 0 组 ABCD,第 1 组是 BC 以及第 2 组 C。

 

Matcher 对象有一些方法可以向我们提供有关组的信息:

 

public intgroupCount( )返回本匹配器的模式中分组的数目。第 0 组不包括在内。

 

public String group( )   返回前一次匹配操作(例如:find())的第 0 组(整个匹配)。

 

public String group(int i)   返回在前一次匹配操作期间指定的组。如果匹配成功,但是指

定的组没有匹配输入字符串的任何部分,将返回 null。

 

public intstart(int group)返回在前一次匹配操作中寻找到的组的起始下标。

 

public intend(int group)返回在前一次匹配操作中寻找到的组的最后一个字符下标加一

的值。

 

下面是正则表达式组的例子:

 

//:c12:Groups.java

importjava.util.regex.*;

importcom.bruceeckel.simpletest.*;

 

public classGroups {

    private static Test monitor = new Test();

    static public final String poem =

        "Twas brillig, and the slithytoves\n" +

        "Did gyre and gimble in thewabe.\n" +

        "All mimsy were theborogoves,\n" +

        "And the mome rathsoutgrabe.\n\n" +

        "Beware the Jabberwock, myson,\n" +

        "The jaws that bite, the clawsthat catch.\n" +

        "Beware the Jubjub bird, andshun\n" +

    "The frumious Bandersnatch.";

    public static void main(String[] args) {

    Matcher m =

     Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$")

                .matcher(poem);

    while(m.find()) {

            for(int j = 0; j <=m.groupCount(); j++)

        System.out.print("[" +m.group(j) + "]");

      System.out.println();

        }

    monitor.expect(new String[]{

            "[the slithy toves]" +

      "[the][slithytoves][slithy][toves]",

      "[in the wabe.][in][thewabe.][the][wabe.]",

            "[were the borogoves,]" +

      "[were][theborogoves,][the][borogoves,]",

      "[mome raths outgrabe.]" +

      "[mome][rathsoutgrabe.][raths][outgrabe.]",

      "[Jabberwock, my son,]" +

      "[Jabberwock,][myson,][my][son,]",

      "[claws that catch.]" +

      "[claws][thatcatch.][that][catch.]",

      "[bird, and shun][bird,][and shun][and][shun]",

      "[The frumiousBandersnatch.][The]" +

      "[frumiousBandersnatch.][frumious][Bandersnatch.]"

        });

    }

} ///:~

 

这首诗来自于 Lewis Carroll 的 Throughthe Looking Glass  中的“Jabberwocky”。我

们可以看到这个正则表达式模式有许多圆括号分组,由任意数目的非空格字符(‘\S+’)伴

随任意数目的空格字符(‘\s+’)所组成。目的是捕获每行的最后 3 个词;每行最后以‘$’结束。

不过,在正常情况下,将‘$’与整个输入序列的末端相匹配。所以我们一定要显式地告知正

则表达式注意输入序列中的换行符。这可以由序列开头的模式标记‘(?m)’来完成(模式标

记马上就会介绍)


原创粉丝点击