publicclassUsePattern{ publicstaticvoidmain(String[] args){ // TODO Auto-generated method stub String str="We call this the live-code approach." +"These examples are available from three locations-they are " +"on the CD that accompanies this book"; Pattern expression = Pattern.compile("[a-zA-Z]+");//创建匹配模式 Matcher matcher=expression.matcher(str);//通过匹配模式得到匹配器 //通过这种方式来进行重复匹配的效率较高 String word=null; int n=0; while(matcher.find())//扫描是否有匹配的子串,如果匹配器没有重置,则从当前下一个还没进行匹配的字符开始匹配 { word=matcher.group();//得到匹配的子串 System.out.println(word+"\t"); if((n+1)%4==0)//每行显示四个单词 System.out.println(); n++; } System.out.print("\n单词总数:"+n); System.out.println("\n单词字母9个及以上的单词有:"); Pattern expression1 = Pattern.compile("[a-zA-Z]{9,}"); Matcher matcher1=expression1.matcher(str); while(matcher1.find()) { word=matcher1.group(); System.out.println(word+"\n"); } System.out.println(); }