Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex - including strings: java

Tags:

java

regex

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

like image 332
JJunior Avatar asked Apr 22 '26 20:04

JJunior


1 Answers

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.*");
like image 174
Sam Barnum Avatar answered Apr 24 '26 17:04

Sam Barnum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!