字符串:正则表达式组和模式标记的使用
??
/* //: strings/Groups.java import java.util.regex.*; import static net.mindview.util.Print.*; public class Groups { static public final String POEM = "Twas brillig,and the slithy tovesn" + "Did gyre and gimble in the wabe.n" + "All mimsy were the borogoves,n" + "And the mome raths outgrabe.nn" + "Beware the Jabberwock,my son,n" + "The jaws that bite,the claws that catch.n" + "Beware the Jubjub bird,and shunn" + "The frumious Bandersnatch."; static { System.out.println(POEM); } public static void main(String[] args) { Matcher m = Pattern.compile("(?m)(S+)s+((S+)s+(S+))$") .matcher(POEM); //由输出可以看到,诗歌有多行组成,程序的意图是要与每行进行匹配 //因此在正则表达式中添加了模式标记(?m),显示的告知正则 //表达式注意输入序列中的换行符。 System.out.println("---------------"); while(m.find()) { //m.groupCount()返回的值为4.组0 不算在内。 for(int j = 0; j <= m.groupCount(); j++) printnb("[" + m.group(j) + "]"); print(); } } } /* Output: Twas brillig,and the slithy toves Did gyre and gimble in the wabe. All mimsy were the borogoves,And the mome raths outgrabe. Beware the Jabberwock,The jaws that bite,the claws that catch. Beware the Jubjub bird,and shun The frumious Bandersnatch. --------------- [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,][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.] *///:~ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |