3

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

2 Answers 2

7

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.*");
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.