Reputation: 2849
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
Upvotes: 3
Views: 158
Reputation: 262554
If you are only interested in matching substrings (as opposed to more complex patterns), you do not need to use regular expressions at all.
if (str.contains(substring))
But I assume you were just simplifying the question.
Upvotes: 0
Reputation: 10714
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.*");
Upvotes: 7