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

时间:2017-10-25 08:05:21

标签: java file file-read

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

我的文件包含:

test 1 START
test2  XYZ
test 3 ABC
test 2 START

它应该打印

test 1 START
test 2 START

我尝试了下面的代码,但它只打印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 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

我认为你已经找到了解决方案。 无论如何,应该有效的正则表达式是:

".*START$"

其中说:采取随机(。*),然后是START和START是行的结尾($)

答案 2 :(得分:0)

您的代码的完整版应如下所示

     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 condition

答案 3 :(得分:-1)

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));
              }
            }