Aish
Aish

Reputation: 185

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++;
     }

Upvotes: 0

Views: 2110

Answers (2)

Jeremy Gurr
Jeremy Gurr

Reputation: 1623

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++;
}

Upvotes: 0

shmosel
shmosel

Reputation: 50716

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++;
    }
}

Upvotes: 1

Related Questions