正则表达式-包括字符串:java

正则表达式-包括字符串:java,java,regex,pattern-matching,Java,Regex,Pattern Matching,我试图从一个文件中打印出符合java中特定模式的行。 我正在使用Pattern类来完成这项工作 我试着用“[哈利]”这个字,这样每一行都会被打印出来。 但模式的计算结果总是错误的。 我的假设是,我输入的正则表达式模式是一个字符串 我的代码如下: try { BufferedReader br = new BufferedReader(new FileReader("test.txt")); Pattern p = Pattern.compile("harry");

我试图从一个文件中打印出符合java中特定模式的行。 我正在使用Pattern类来完成这项工作

我试着用“[哈利]”这个字,这样每一行都会被打印出来。 但模式的计算结果总是错误的。 我的假设是,我输入的正则表达式模式是一个字符串

我的代码如下:

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();
      }
请帮忙。我不明白代码在哪里被破坏。我正在尝试不同的模式匹配,但这是正确的方法吗


谢谢问题是
匹配器。匹配项必须匹配整个字符串。使用
Matcher.find
,或更改模式以允许使用前导字符和尾随字符

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

如果您只对匹配子字符串感兴趣(与更复杂的模式相反),则根本不需要使用正则表达式

if (str.contains(substring))
但我想你只是在简化问题