简体   繁体   中英

Count number of occurrences of a pattern in a text file using regex in Java

I am reading a text from a file and trying to count number of occurrence of the words Lady, Lucy and Lazy. I am expecting a count of 3 but getting 0. Please help me to find what is wrong here.

FileReader r= new FileReader("C:\\Users\\beath.txt");           
BufferedReader bfr=new BufferedReader(r);
String x="L[a-z]{2}y";
String Y="";

 while ((Y=bfr.readLine())!=null)
 {
     String[] words = Y.split(" ");
     Pattern p = Pattern.compile(x);
     for (String word : words)
       m = p.matcher(word);
      if(m.find())   
      count++;
     }

You're only matching the last word on each line. Here's your code correctly formatted:

while ((Y=bfr.readLine())!=null)
{
    String[] words = Y.split(" ");
    Pattern p = Pattern.compile(x);
    for (String word : words)
        m = p.matcher(word);

    // this only happens after the for loop!!
    if(m.find())
        count++;
}

To fix, simply include the if in the body of the loop by using curly braces:

while ((Y=bfr.readLine())!=null)
{
    String[] words = Y.split(" ");
    Pattern p = Pattern.compile(x);
    for (String word : words) {
        m = p.matcher(word);
        if(m.find())
            count++;
    }
}

One problem is that your for() loop only applies to the "m = p.matcher(word);" line, since you don't have braces around anything else. So the "if(m.find()) count++;" code only executes once per line, not once per word. So it will only match if Lady for example is the last word in the line.

You probably meant to do this:

for (String word : words) {
    m = p.matcher(word);
    if(m.find())   
        count++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM