Anthony
Anthony

Reputation: 3

How to find simple word in Java file?

I need help. I'm beginning programmer, I try to make program with regular expression. I try to find every life word in my file. I have code like this:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class myClass {

    public int howManyWord () {
        int count = 0;      
        try {
            BufferedReader br = new BufferedReader(new FileReader("C:/myFile.txt"));
            String line = "";
            while ((line = br.readLine()) != null) {
                Matcher m = Pattern.compile("life").matcher(line);
                while (m.find()) {
                    System.out.println("found");
                    count++;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return count;       
    }
}    

That works. I try to change this because when I'm searching my word and when compilator find something like this "lifelife" count is 2. What should I change?

Sorry for my English but help me, please.

Upvotes: 0

Views: 77

Answers (2)

Diyarbakir
Diyarbakir

Reputation: 2099

Use Pattern p = Pattern.compile("\\blife\\b"); and set the pattern once before the while loop.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class myClass {

public int howManyWord () {
    int count = 0;      
    try {
        BufferedReader br = new BufferedReader(new FileReader("C:/myFile.txt"));
        String line = "";
        Pattern p = Pattern.compile("\\blife\\b"); // compile pattern only once
        while ((line = br.readLine()) != null) {
            Matcher m = p.matcher(line);
            while (m.find()) {
                System.out.println("found");
                count++;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return count;       
}
}  

Upvotes: 1

pkalinow
pkalinow

Reputation: 1741

"(?<=^|\\W)life(?=$|\\W)" will find words "life" but not "lifelife" or "xlife".

Upvotes: 0

Related Questions