I need to make strict validation of input for my project, time in format HH:MM am/pm. So far i've got this RegEx expression:
(1[012]|[1-9]):[0-5][0-9](\\s)?(?i)(am|pm)
Above expression working fine but when I pass 09:05 AM its not working and its working when i pass 9:05 AM
Can some one suggest me please how can i solve this problem.
Code
public class SampleClass {
public static void main(String[] args) {
String inputTimeString = "09:05 PM";
boolean isValidaTim = isValidTime(inputTimeString);
if (isValidaTim) {
System.out.println("Valid time string: " + inputTimeString);
} else {
System.out.println("Invalid time string: " + inputTimeString);
}
}
public static boolean isValidTime(String time) {
String regexPattern = "(1[012]|[1-9]):" + "[0-5][0-9](\\s)" + "?(?i)(am|pm)";
Pattern compiledPattern = Pattern.compile(regexPattern);
if (time == null) {
return false;
}
Matcher m = compiledPattern.matcher(time);
return m.matches();
}
}
09and you can use a character class for the am pm part(?:1[012]|0?[1-9]):[0-5][0-9]\\h?(?i)[ap]mSee regex101.com/r/0ien3M/1