🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### [组(Groups)](https://lingcoder.gitee.io/onjava8/#/book/18-Strings?id=%e7%bb%84%ef%bc%88groups%ef%bc%89) 组是用括号划分的正则表达式,可以根据组的编号来引用某个组。组号为 0 表示整个表达式,组号 1 表示被第一对括号括起来的组,以此类推。因此,下面这个表达式, ~~~ A(B(C))D ~~~ 中有三个组:组 0 是`ABCD`,组 1 是`BC`,组 2 是`C`。 `Matcher`对象提供了一系列方法,用以获取与组相关的信息: * `public int groupCount()`返回该匹配器的模式中的分组数目,组 0 不包括在内。 * `public String group()`返回前一次匹配操作(例如`find()`)的第 0 组(整个匹配)。 * `public String group(int i)`返回前一次匹配操作期间指定的组号,如果匹配成功,但是指定的组没有匹配输入字符串的任何部分,则将返回`null`。 * `public int start(int group)`返回在前一次匹配操作中寻找到的组的起始索引。 * `public int end(int group)`返回在前一次匹配操作中寻找到的组的最后一个字符索引加一的值。 下面是正则表达式组的例子: ~~~ // strings/Groups.java import java.util.regex.*; public class Groups { public static final String POEM = "Twas brillig, and the slithy toves\n" + "Did gyre and gimble in the wabe.\n" + "All mimsy were the borogoves,\n" + "And the mome raths outgrabe.\n\n" + "Beware the Jabberwock, my son,\n" + "The jaws that bite, the claws that catch.\n" + "Beware the Jubjub bird, and shun\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(); } } } /* Output: [the slithy toves][the][slithy toves][slithy][toves] [in the wabe.][in][the wabe.][the][wabe.] [were the borogoves,][were][the borogoves,][the][borogoves,] [mome raths outgrabe.][mome][raths outgrabe.][raths][outgrabe.] [Jabberwock, my son,][Jabberwock,][my son,][my][son,] [claws that catch.][claws][that catch.][that][catch.] [bird, and shun][bird,][and shun][and][shun] [The frumious Bandersnatch.][The][frumious Bandersnatch.][frumious][Bandersnatch.] */ ~~~ 这首诗来自于 Lewis Carroll 所写的*Through the Looking Glass*中的 “Jabberwocky”。可以看到这个正则表达式模式有许多圆括号分组,由任意数目的非空白符(`\\S+`)及随后的任意数目的空白符(`\\s+`)所组成。目的是捕获每行的最后3个词,每行最后以`\$`结束。不过,在正常情况下是将`\$`与整个输入序列的末端相匹配。所以我们一定要显式地告知正则表达式注意输入序列中的换行符。这可以由序列开头的模式标记`(?m)`来完成(模式标记马上就会介绍)。