Regex - including lines: java

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) {
        // TODO Auto-generated catch block
        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

+3
source share
2 answers

Matcher.matches . Matcher.find, , .

Pattern p = Pattern.compile(".*harry.*");
+7

( ), .

if (str.contains(substring))

, .

0

Source: https://habr.com/ru/post/1767100/


All Articles