javastringdatetimetimetimeofday

Java - How do i find out that a string is in the correct format using pattern matching


My string value;

09:00-10:00,12:00-14:30,16:00-18:00 (this string repeats time intervals n times like this)

and I want to find out that a string is in the correct format using pattern matching;

Pattern.matches("<Pattern Here>", stringValue);

is it possible?

I tried;

Pattern.matches("^[0-9:0-9-0-9:0-9,]+$", value);

But doesn't work properly


Solution

  • You can use the following pattern for any given range of 2 times in the form of 24h clock:

    private static final String HOURLY_TIME_PATTERN = "([01][0-9]|2[0-3]):([0-5][0-9])";
    private static final String TIME_RANGER_PATTERN = HOURLY_TIME_PATTERN + "-" + HOURLY_TIME_PATTERN;
    private static final String PATTERN = "^" + TIME_RANGER_PATTERN + "(," + TIME_RANGER_PATTERN + "?)*$";
    private static final Pattern pattern = Pattern.compile(PATTERN);
    
    public static void main(String[] args) {
        String input = "09:00-10:00,12:00-14:30,16:00-18:00";
        if (pattern.matcher(input).matches()) {
            System.out.println("We have a match!");
        }
    }
    

    Explanation: