有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java需要帮助读取日志中以特定单词结尾的特定行

我需要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));
              }
            }

共 (4) 个答案

  1. # 1 楼答案

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

    ".*START$"
    

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

  2. # 2 楼答案

    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));
                  }
                }
    
  3. # 3 楼答案

    代码的完整版本如下所示

         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条件即可

  4. # 4 楼答案

    line.endsWith("START")检查就足够了。这里不需要正则表达式