正则表达式之Groups(组)- m.group()

正则表达式之Groups(组)- m.group()

import java.util.regex.*;
import static net.mindview.util.Print.*;

public class Groups {
     static public 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) {
           // ?m 启用多行模式
           Matcher m = Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$").matcher(POEM);
           while (m.find()) {
                for (int j = 0; j <= m.groupCount(); j++){
                      printnb("[" + m.group(j) + "]");
                }
                print();
           }
     }
}

输出:


[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.]

可以看到,正则表达式"(?m)(\S+)\s+((\S+)\s+(\S+))$"由许多圆括号组成,由任意数目的非空格字符(\S+)及随后的任意数目的空格字符(\s+)所组成。目标是捕获每行的最后三个词,每行最后以$结束。不过,在正常情况下是将$与整个输入序列的末端相匹配。所以我们一定要显示地告知正则表达式注意输入序列中的换行符。这可以由序列开头的模式标记(?m)来完成。

我的问题:对于输出结果,一开始我总是看不懂为什么是
[the slithy toves][the][slithy toves][slithy][toves]

  1. 我再次阅读了一下组的概念,发现组是用括号划分的正则表达式,每一个括号中的内容就是一个字符串,也就是说,出现了多少对括号,就有多少组。并且组的编号是从1开始计算的。
  2. 我一开始仅仅是阅读了一下概念文字,下意识的认为自己已经读懂了这个概念,实际上是压根就不懂。所以才导致程序运行结果出来时,我完全看不懂为什么出现了四个字符串。
  3. 由此可见,平时在阅读时,切记囫囵吞枣,似懂非懂,一定要对概念有一个清晰地认识。这和大学时学习极限的概念是一致的,不仅要理解内涵,还要知道它的外延。
    组的概念

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值