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

版权声明:本文章仅用于个人学习及技术探索,若有侵权,请邮件联系[email protected] https://blog.csdn.net/qq_33546330/article/details/89923826

正则表达式之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. 由此可见,平时再阅读时,切记囫囵吞枣,似懂非懂,一定要对概念有一个清晰地认识。这和大学时学习极限的概念是一致的,不仅要理解内涵,还要知道它的外延。
    组的概念

猜你喜欢

转载自blog.csdn.net/qq_33546330/article/details/89923826