Skip to content
Advertisement

how to write regex expression to find date and time

I am reading a file and looking for this string in the file.looking to capture the value(00:00:22) using regex.I have written regular expression but its not finding that value?

"20.10.02 00:00:22:135 INFO Running Cron : BatchJob"

Pattern p = Pattern.compile("([01][0-9]|2[0-3]):([01][0-9]|2[0-3])  INFO       Running Cron", Pattern.CASE_INSENSITIVE);
                        Matcher m = p.matcher(line);
                            System.out.println(m.find());

Advertisement

Answer

  1. Use the regex, \d{1,2}:\d{1,2}:\d{1,2} which means three combinations of 1 or 2 digits separated by :
  2. Use m.find() as the condition and m.group() to print the matched string.

Demo:

import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) throws ParseException {
        String line = "20.10.02 00:00:22:135 INFO Running Cron : BatchJob";
        Pattern p = Pattern.compile("\d{1,2}:\d{1,2}:\d{1,2}");
        Matcher m = p.matcher(line);

        if (m.find()) {
            System.out.println(m.group());
        }
    }
}

Output:

00:00:22
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement