我用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;
}可是现在是在想不出该怎么写正则表达式,请大虾们帮忙~
思路如下: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;
}可是现在是在想不出该怎么写正则表达式,请大虾们帮忙~
Pattern patternOfWord = Pattern.compile("这里要写上正则表达式");//写上你要的单词啊
[/Quote]
单纯写上单词没用啊,除非一行只有这一个单词,不然不会被识别到,正则我尝试了很久,误解
谁知道这样的正则表达式该怎么写
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;
}
写上单词就可以,两边加个空格。
if (m.matches())//如果匹配
改为if (m.find())