Hi Celauran!
Looks like you've written a nice long expression... Cool!
Let's see if we can tweak it as you were asking.
First thing that jumps at me: you have four places with a 1 in square brackets: {1}
You can remove those. Any time you have a character class, it already means "match one of these", unless you have a quantifier.
Second tiny optimization: you can take the "M" out of (AM|PM), yielding something like:
Third thought: On the line above, you can see some non-capturing groups. Your expression has four capturing groups. If you don't plan to capture anything, you can get rid of that overhead by using non-capturing groups. Or, in the case of the lone space character (\s), forget the group altogether.
One more idea: some places use different dividers for the hours and minutes, or none at all. For instance, 1855, or 12.44. So you could add characters in that class, or make it optional.
Also: no need to insert a single digit in a character class, as in the two instances of [\d]
If we make all these tweaks, here's where we are so far (without the delimiters):
Code: Select all
(?i)^(?:[01]?\d|2[0-3])[.:h]?[0-5]\d\s?(?:(?:A|P)M)?
But oops, if you have no AM or PM, this will capture a space character after the time! So you need to make the space character part of the AM PM option. Let's fix this:
Code: Select all
(?i)^(?:[01]?\d|2[0-3])[.:h]?[0-5]\d\(?:s?(?:(?:A|P)M))?
But wait a minute... As it is, the expression allows 08:55 pm and 22:22am. You need to decide if you want to validate the date as well or not. If so, you'll have to capture the hour and control the am pm with conditionals. And we can no longer break the hour at 00-19 vs 20-24. Instead, we need to test for 00 to 12 vs everything else. (If you think 12:33pm is legit). This is where it leads us:
Code: Select all
(?i)^(?:([0]?\d|1[012])|(?:1[3-9]|2[0-3]))[.:h]?[0-5]\d(?:\s?(?(1)(?:(?:A|P)M)))?
There might still be a bug or two in there, but without spending an hour on it, that's how I would start debugging your expression.
Hope this is the kind of info you were looking for!
Wishing you a fun day.