1 package test_21_2; 2 3 import java.util.HashSet; 4 import java.util.Set; 5 import java.util.regex.Matcher; 6 import java.util.regex.Pattern; 7 8 public class RegularTest { 9 10 public static void main(String[] args) { 11 12 String str = "Twas brillig, and the slithy toves\n" + 13 "Did gyre and gimble in the wabe.\n" + 14 "All mimsy were the borogoves,\n" + 15 "Beware the Jabberwock, my son,\n" + 16 "The jaws that bite, the claws that catch.\n" + 17 "Beware the Jubjub bird, and shun\n" + 18 "The frumious Bandersnatch."; 19 // 找出所有不以大写字母开头的词,不重复地计算其个数 20 String regex = "\\b[a-z]\\w+"; 21 22 Matcher m = Pattern.compile(regex).matcher(str); 23 24 Set<String> set = new HashSet<String>(); 25 26 while (m.find()) { 27 set.add(m.group()); 28 } 29 30 System.out.println(set.size()); 31 } 32 }
结果如下:
22