Solved: regex pattern for time

Regex, or Regular Expression, is a sequence of characters that forms a search pattern. This pattern can be employed in performing a variety of tasks such as validation, matching, and replacement, amongst others. In Java, regex is an essential tool utilized when dealing with strings. In this article, we’ll look at how to create a regex pattern for time.

The task is to construct a regex pattern that can validate a conventional 12-hour format time, like ’12:00 AM’ or ’01:45 PM’.

public class Main {
    public static void main(String[] args) {
        // Test the pattern
        System.out.println("12:30 PM".matches("^((1[0-2]|0?[1-9]):([0-5][0-9])\s?([AaPp][Mm]))$"));  // returns true
    }
}

This pattern `^((1[0-2]|0?[1-9]):([0-5][0-9])\s?([AaPp][Mm]))$` is constructed with the following rationale:
– `1[0-2]|0?[1-9]`: This part of the pattern checks for the hour. It recognizes any digit from 01-09 and 10-12. The ‘0?’ denotes that the leading zero is optional.
– `:` this is a literal symbol that matches the colon in the input.
– `[0-5][0-9]`: This part checks for the minutes. It accepts any number from 00 to 59.
– `\s`: Matches a whitespace character.
– `[AaPp][Mm]` – This part checks for either AM or PM. This enables the input to accept both lowercase and uppercase characters.

This pattern ultimately ensures a perfectly formatted 12-hour time.

Java and Regex


The Java language has incorporated regex since the 1.4 version. To facilitate regex operations, Java developed `java.util.regex`, a package with three classes: `Pattern`, `Matcher`, and `PatternSyntaxException`. The `Pattern` class simplifies the initiation of regex operations, while the `Matcher` class is necessary for performing matching operations. Lastly, `PatternSyntaxException`, a subclass of `IllegalArgumentException`, denotes any syntax error in a regular expression pattern.

  • `Pattern.compile(String regex)`: This static method from the `Pattern` class compiles the regular expression and assigns it to a Pattern.
  • `Pattern matcher(CharSequence input)`: This instance method create a matcher that will match the regular expression against the input.

Deciphering Regex Patterns

Grasping regex patterns can appear daunting initially due to the heavy usage of special characters. However, a closer look can decipher any pattern:
– ‘^’ is an anchor character that denotes the start of a line. ‘$’ denotes the end. Thus, together they ensure a full string match and not just a substring match.
– ‘1[0-2]|0?[1-9]’ matches any digit from 01-09 or 10-12. With ‘|’, regex either takes the left or the right operand.
– ‘[0-5][0-9]’ is a digit range that matches any digit from 00-59.
– ‘s’ matches any whitespace character.
– The brackets ‘[ ]’ define a character class, letting you list multiple characters to match.

Understanding these individual building blocks opens up a whole world of pattern matching possibilities, making regex a powerful tool in any developer’s toolkit.

Related posts:

Leave a Comment