我用BufferedReader将文件的内容一行一行的读出来,我现在需要统计某个单词在文件里出现的次数,但要求必须用正则表达式
思路如下:
- Java code
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; }
可是现在是在想不出该怎么写正则表达式,请大虾们帮忙~
------解决方案--------------------
for example
- Java code
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; }
------解决方案--------------------
Pattern patternOfWord = Pattern.compile("这里要写上正则表达式");
写上单词就可以,两边加个空格。
if (m.matches())//如果匹配
改为if (m.find())