Java Regular Expression Matching for hh:mm:ss in String

Seems like an unnecessarily complicated pattern.... why not just (if you are doing line-by-line processing):

"^(\\d\\d:\\d\\d:\\d\\d)"

If you are doing multi-line processing you will want to use:

"(?m)^(\\d\\d:\\d\\d:\\d\\d)"

Here's some example code and output:

public static void main(String[] args) {
    final Pattern pattern = Pattern.compile("(?m)^(\\d\\d:\\d\\d:\\d\\d)");
    final Matcher matcher = pattern.matcher("00:02:10-XYZ:Count=10\n00:04:50-LMK:Count=3");
    while(matcher.find())
    {
        System.out.printf("[%s]\n", matcher.group(1));
    }        
}

outputs

[00:02:10]
[00:04:50]

I did with this way.

00:02:10-XYZ:Count=10
00:04:50-LMK:Count=3

Pattern pattern = Pattern.compile("([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])");
//File Beginning Time
for(int x = 0; x < file_content.size(); x++)
   {
        matcher= pattern.matcher(file_content.get(x));
        ListMatches = new ArrayList<String>();
        if(matcher.find())
          {
                start_time = matcher.group();
                break;
          }                
    }
//File End Time
for(int x = file_content.size()-1; x > 0 ; x--)
        {
            matcher= pattern.matcher(file_content.get(x));
            listMatches = new ArrayList<String>();
            if(matcher.find())
            {
                end_time = matcher.group();
                break;
            }                  
        }

Don't use regex for this, use a SimpleDateFormat. This has two massive advantages

  1. The code in SimpleDateFormat is tested and robust
  2. The SimpleDateFormat will validate to ensure that you have real time numbers

This would look something like this:

public static void main(String[] args) throws Exception {
    final String s = "00:02:10-XYZ:Count=10\n"
            + "00:04:50-LMK:Count=3";
    final Scanner sc = new Scanner(s);
    final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    while(sc.hasNextLine()) {
        final String line = sc.nextLine();
        final Date date = dateFormat.parse(line);
        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        System.out.println(calendar.get(Calendar.HOUR));
        System.out.println(calendar.get(Calendar.MINUTE));
        System.out.println(calendar.get(Calendar.SECOND));
    }
}

Output:

0
2
10
0
4
50

From the javadoc for DateFormat.parse:

Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.

So the SimpleDateFormat will parse the String until it reads the whole pattern specified then stops.

Tags:

Time

Java

Regex