package thinkjava13; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; public class A05Groups { public static final String POEM="Twas briling,and the slithy toves\n"+ "Did gyre and gimble in the wabe,"+ "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 claww that catch. \n"+ "Beware the Jubjub bird,and shun\n"+ "The frumious Bandersnath."; public static void main(String args[]){ //(?m):打开多行模式 Matcher m=Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$").matcher(POEM); while(m.find()){ for(int i=0;i<=m.groupCount();i++){ System.out.print(i+"->【"+m.group(i)+"】\t"); } System.out.println(); } System.out.println("-----------------------------------"); Matcher m1=Pattern.compile("(?m)\\W([a-z]+)\\W").matcher(POEM); Set<String> set=new HashSet<String>(); int count=0; int total=0; while(m1.find()){ String word=m1.group(1); if(set.contains(word)){ total++; }else{ count++; set.add(word); } m1.region(m1.end()-1, POEM.length()); } System.out.println("总共匹配非重复个数:"+count+"\t重复:"+total); System.out.println(set); } /** * 输出结果如下: * 0->【the slithy toves】 1->【the】 2->【slithy toves】 3->【slithy】 4->【toves】 0->【in the wabe,】 1->【in】 2->【the wabe,】 3->【the】 4->【wabe,】 0->【the borogoves ,】 1->【the】 2->【borogoves ,】 3->【borogoves】 4->【,】 0->【mome raths outgrabe.】 1->【mome】 2->【raths outgrabe.】 3->【raths】 4->【outgrabe.】 0->【Jabberwock. my son,】 1->【Jabberwock.】 2->【my son,】 3->【my】 4->【son,】 0->【Jubjub bird,and shun】 1->【Jubjub】 2->【bird,and shun】 3->【bird,and】 4->【shun】 0->【The frumious Bandersnath.】 1->【The】 2->【frumious Bandersnath.】 3->【frumious】 4->【Bandersnath.】 ----------------------------------- 总共匹配非重复个数:25 重复:15 [briling, catch, jaws, shun, raths, were, borogoves, claww, mome, frumious, son, the, in, my, wabe, gimble, and, bird, that, bite, slithy, mimsy, outgrabe, gyre, toves] */ }
原文:http://blog.csdn.net/ztt_1119/article/details/44652433