Search code examples
javafilefile-read

Need help to read specific line in a log which ends with specific word


I need help on java code to read a log file that can print all lines present ends with START word.

my file contains:

test 1 START
test2  XYZ
test 3 ABC
test 2 START

it should print

test 1 START
test 2 START

I tried below code but it printing START only.

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

Solution

  • I think you already found your solution. Anyway a regex that should work is:

    ".*START$"
    

    which says: take everithing (.*) that is followed by START and START is the end of the line ($)