Matching a time interval using regex What I needed to do was check whether a given string matches a certain pattern. The pattern is this:

00:00:00,000 --&gt; 00:00:00,000


Things to keep in mind:

The 0s can be numbers from 0 to 9.

The pattern must be alone in a single line; the line has to only consist of the pattern.

I came up with this:

"^(\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d) --&gt; (\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d)"


I tested it a few times and strings that respect the pattern return true, the ones that don't, return false, as they should.

Here's a test case:

import java.util.regex.Pattern;

public class TestCaseRegex {

    public static void main(String[] args) {
        //will return true
        String testOne = "00:01:23,846 --&gt; 00:01:26,212";

        //will return false, there's a letter where a number should be
        String testTwo = "00:01:23,84a --&gt; 00:01:21,221"; 

        //will return true
        String testThree = "00:05:54,846 --&gt; 00:01:16,450"; 

        //will return false. The string doesn't match the format.
        String testFour = "00:05:54,6 --&gt; 00:0116,450"; 

        System.out.println(patternMatch(testOne));
        System.out.println(patternMatch(testTwo));
        System.out.println(patternMatch(testThree));
        System.out.println(patternMatch(testFour));
    }

    public static boolean patternMatch(String str) {
        Pattern p = Pattern.compile("^(\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d) "
                + "--&gt; (\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d)");
        return p.matcher(str).matches();
    }

}


As I'm very new to regex, I'm wondering if this is the most efficient/correct way to accomplish this.
Rather than using \d, you might want to limit the matcher to valid ranges. 

\d{2}:([0-5]\d:){2},\d{3}


would match either of the timestamps and it would prevent someone from entering

11:88:88,888 --&gt; 12:99:99,999