书上的作业要求:
 找出字符串“this IS My test,Please help Me”中以小写字母开头的单词,并计算出其中不重复单词的个数!
 要求主要用正则表达式!
 如果我自己写的话,计算不重复单词的个数要用数组的遍历了
 可是书上是在讲了正则之后留得作业,所以估计不会这么麻烦!
 希望高手指点
 

解决方案 »

  1.   

    import java.util.HashSet;
    import java.util.Set;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class Child {
    public static void main(String ...strings ){
    String s = "this IS My test,Please help Me";
    Set<String> set = new HashSet<String>();
    Pattern p = Pattern.compile("\\b[a-z][a-zA-Z]*");
    Matcher m = p.matcher(s);
    System.out.println("小写字母开头的单词:");
    while(m.find()){
    System.out.println(m.group());
    set.add(m.group());
    }
    System.out.println("不重复单词的个数:"+set.size());
    }
    }
    刚回了你的帖子........
      

  2.   

    有没有人想到怎么样出regex去去掉重复的单词?
      

  3.   

    String lowercaseStartsWords = str.replaceAll("\\b[A-Z]\\w*\\b\\s*", "");  //小写字母开头
    String uniqueWords = str.replaceAll("(?i)\\b(\\w+)\\b\\s*(?=.*\\b\\1\\b)", "");  //不重复单词