我用BufferedReader将文件的内容一行一行的读出来,我现在需要统计某个单词在文件里出现的次数,但要求必须用正则表达式
思路如下:public int computeNumOfWord (String word){//查找的单词
this.openReader();

String lineStr = new String();
int countOfWord = 0;
Pattern patternOfWord = Pattern.compile("这里要写上正则表达式");
Matcher m; try {
while ( (lineStr = this.in.readLine()) != null ){
 m = patternOfWord.matcher(lineStr);
 if (m.matches())//如果匹配
 countOfWord++;//则+1
}
this.closeReader();
return countOfWord;
}
catch (IOException e) {
e.printStackTrace();
}
this.closeReader();
return 0;
}可是现在是在想不出该怎么写正则表达式,请大虾们帮忙~

解决方案 »

  1.   

      Pattern patternOfWord = Pattern.compile("这里要写上正则表达式");//写上你要的单词啊
      

  2.   

    你这个思路上 有漏洞啊 一行中这个单词出现多次 怎么办 你还 countOfWord++;//则+1这样不是漏掉次数了吗
      

  3.   

    Java code
      Pattern patternOfWord = Pattern.compile("这里要写上正则表达式");//写上你要的单词啊
    [/Quote]
    单纯写上单词没用啊,除非一行只有这一个单词,不然不会被识别到,正则我尝试了很久,误解
    谁知道这样的正则表达式该怎么写
      

  4.   

    建议楼主还是不要按行读取 ,读出来放到StringBuffer里依次遍历查找
      

  5.   

    for example
    public int computeNumOfWord (String word){//查找的单词
            this.openReader();
            
            String lineStr = new String();
            int countOfWord = 0;
            Pattern patternOfWord = Pattern.compile(word); //就是查找的单词
            Matcher m;        try {
                while ( (lineStr = this.in.readLine()) != null ){
                     m = patternOfWord.matcher(lineStr);
                     //if (m.matches())//如果匹配
                       while (m.find()) //如果能找到匹配
                         countOfWord++;//则+1
                }
                this.closeReader();
                return countOfWord;
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            this.closeReader();
            return 0;
        }
      

  6.   

    Pattern patternOfWord = Pattern.compile("这里要写上正则表达式");
    写上单词就可以,两边加个空格。
    if (m.matches())//如果匹配
    改为if (m.find())