I am trying to print lines from a file that match a specific pattern in java. For this, I use the Pattern class.
I tried putting patter as "[harry]" so that every line that has "harry" is printed. But the template always evaluates to false. My guess is that the regex pattern that I entered 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) {
e.printStackTrace();
}
Please, help. I do not understand where the code breaks. I am trying to use different templates, but is this the right way to do this?
thank
source
share