I am trying to print out lines from a file which match a particular pattern in java. I am using the Pattern class for doing this.
I tried putting the patter as "[harry]" so that every line which has "harry" gets printed out. But pattern always evaluates to false. My assumption is that the regex pattern I am entering is a string.
My code is as follows:
try {
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
Pattern p = Pattern.compile("harry");
String str = null;
try {
while((str = br.readLine())!=null){
Matcher match = p.matcher(str);
boolean b = match.matches();
if(b){
System.out.println(str);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Please help. I am not understanding where the code is breaking. I am trying different pattern matches but is this the correct way to do it?
Thanks
The problem is Matcher.matches must match the entire string. Either use Matcher.find, or change your pattern to allow leading and trailing characters.
Pattern p = Pattern.compile(".*harry.*");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With