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.