tags:

views:

59

answers:

1
+4  A: 

Try this:

^((?<hours>([012]?\d)|(3[01])):)?(?<minutes>[0-5]?\d)$

You have some problems with your regex. Mostly, you're using * where you shouldn't. This opens the door to many errors. For example, it matches the string "0010203333333".

Kobi
with just a little fix (3?[01]) it worked!why * opens a way to errors, isn't both equivalent to {0,1}?
serhio
Not at all. `*` means zero or more times: {0,∞} ! And you don't need `3?[01]` - 0 and 1 are already covered by `[012]?\d`.
Kobi
ah, yeah... thanks!
serhio
and `\:` means `[\:]` not just `[:]`?
serhio
`:` has no special meaning in there, so you don't have to escape that with `\:` (it is mostly ignored by regex engines, because people escape all kind of characters anyway). `[123]` means "one of these characters", but '[3]' just means "one of the character 3" - it is redundant for a single character, it is the same as `3`.
Kobi