Java 需要帮助阅读日志中以特定单词结尾的特定行吗

Java 需要帮助阅读日志中以特定单词结尾的特定行吗,java,file,file-read,Java,File,File Read,我需要java代码的帮助来读取一个日志文件,该文件可以打印所有以起始字结尾的行 我的文件包含: test 1 START test2 XYZ test 3 ABC test 2 START 应该打印出来 test 1 START test 2 START 我尝试了下面的代码,但它只是开始打印 public class Findlog{ public static void main(String[] args) throws IOException { Buffered

我需要java代码的帮助来读取一个日志文件,该文件可以打印所有以起始字结尾的行

我的文件包含:

test 1 START
test2  XYZ
test 3 ABC
test 2 START
应该打印出来

test 1 START
test 2 START
我尝试了下面的代码,但它只是开始打印

 public class Findlog{
    public static void main(String[] args) throws IOException {

    BufferedReader r = new BufferedReader(new FileReader("myfile"));
    Pattern patt = Pattern.compile(".*START$");
            // For each line of input, try matching in it.
            String line;
            while ((line = r.readLine()) != null) {
              // For each match in the line, extract and print it.
              Matcher m = patt.matcher(line);
              while (m.find()) {
                // Simplest method:
                // System.out.println(m.group(0));

                // Get the starting position of the text

                System.out.println(line.substring(line));
              }
            }

line.endsWith(“开始”)
检查就足够了。这里不需要正则表达式。

我想您已经找到了解决方案。 无论如何,应该起作用的正则表达式是:

".*START$"

上面写着:取后跟START的所有(.*),START是行的结尾($)

代码的完整版本如下所示

     public class Findlog{
        public static void main(String[] args) throws IOException {

        BufferedReader r = new BufferedReader(new FileReader("myfile"));
        String line;
        while ((line = r.readLine()) != null) {
          // For each match in the line, extract and print it.
          if(line.endsWith("START"))
          {
             System.out.println(line);
          }
        }
如果您想跳过区分大小写,那么代码应该如下所示

public class Findlog{
        public static void main(String[] args) throws IOException {

        BufferedReader r = new BufferedReader(new FileReader("myfile"));
        String line;
        while ((line = r.readLine()) != null) {
          // For each match in the line, extract and print it.
          if(line.toLowerCase().endsWith(matches.toLowerCase()))
          {
             System.out.println(line);
          }
        }

只需更改if条件

字符串中有一个名为
endsWith
的方法。为什么不用它来代替正则表达式呢?除此之外,您当前的问题很简单,不是打印您在中读取的
,而是打印正则表达式匹配的行的一部分,也就是“开始”。非常感谢,哦,天哪,我使用了行并删除了子字符串,它按预期工作。
public class Findlog{
        public static void main(String[] args) throws IOException {

        BufferedReader r = new BufferedReader(new FileReader("myfile"));
        String line;
        while ((line = r.readLine()) != null) {
          // For each match in the line, extract and print it.
          if(line.toLowerCase().endsWith(matches.toLowerCase()))
          {
             System.out.println(line);
          }
        }