0

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();
    }

}
6
  • Must you use a regex? Commented Nov 12, 2020 at 2:53
  • No its mandatory to use .I want working code Commented Nov 12, 2020 at 2:54
  • So using a regex is required?? Or could you use LocalTime? Commented Nov 12, 2020 at 2:57
  • For a match only, you don't need the capturing groups. You have to add an optional zero to match 09 and you can use a character class for the am pm part (?:1[012]|0?[1-9]):[0-5][0-9]\\h?(?i)[ap]m See regex101.com/r/0ien3M/1 Commented Nov 12, 2020 at 8:56
  • 1
    Regex is overkill here. See the use of java.time classes shown in Answer by Ole V.V. Commented Nov 16, 2020 at 0:38

3 Answers 3

2

java.time

Don’t use a regular expression for this. Use java.time, the modern Java date and time API.

private static final DateTimeFormatter timeFormatter = new DateTimeFormatterBuilder()
        .parseCaseInsensitive()
        .appendPattern("h:mm a")
        .toFormatter(Locale.ENGLISH);

public static boolean isValidTime(String time) {
    try {
        LocalTime.parse(time, timeFormatter);
        return true;
    } catch (DateTimeParseException dtpe) {
        return false;
    }
}

To try it out:

    System.out.println("Is 9:05 am valid? " + isValidTime("9:05 am"));
    System.out.println("Is 09:05 PM valid? " + isValidTime("09:05 PM"));

Output:

Is 9:05 am valid? true
Is 09:05 PM valid? true

If you want to allow single-digit minutes and permit omitting the space, write your pattern like this:

        .appendPattern("h:m[ ]a")
Is 09:10PM valid? true
Is 09:5 PM valid? true

For most purposes you should also keep the LocalTime object that results from parsing rather than keep your time in a string.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Sign up to request clarification or add additional context in comments.

Comments

1

Just go through the regex. You start with 1[012]|[1-9]. So, either 10, or 11, or 12, or a single non-zero digit. Update the second part, and note that 00 is also a valid hour: 1[012]|0?[0-9] will get the job done. There are many regex tutorials and testers out there.

You then shove a question mark as first char in the final bit for am/pm - whatever is that about? That's making the last digit of minute optional, that seems bizarre; it means 10:5 matches but 10:6 won't. You presumably want to allow spaces in between, so toss a \\s* in there too.

1 Comment

Thanks working now.But if i pass 09:10PM or 09:5 PM it should allow can you suggest please
0

I'd try this one (\d|0\d|1[012]):([0-5]\d)\s*(am|pm)

The hour (\d|0\d|1[012]) can be a single digit, a zero and a single digit or 10,11,12

The minute ([0-5]\d) can be a 0 to 5 followed by a second digit

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.