And now for something completely different... a random regular expression challenge.
The Requirement
Recently I needed to modify an ASP.NET RegularExpressionValidator that previously allowed entry of a number of hours between 1 and 24. The new requirement was to support data entry in multiple hour and minute formats, for example:
Minutes were to be supported down to 5 minute granularity.
The Solution
Here's the nasty looking regular expression I came up with:
^(([1-9]|1[0-9]|2[0-3])[hH][ ]?[0-5]?[05]([mM]?))|((5|[1-9]{1,2}[05])[mM])|(([1-9]|1[0-9]|2[0-4])([hH]?))$
This looks pretty unmanageable, but really it's just three separate regexes orred together:
- ([1-9]|1[0-9]|2[0-4])([hH]?) – matches 1-24 or 1-24h
- (5|[1-9]{1,2}[05])[mM] – matches 5m - 995m in 5m blocks
- ([1-9]|1[0-9]|2[0-3])[hH][ ]?[0-5]?[05]([mM]?) – matches 1-23h0-55m with or without a space inbetween and with or without the trailing "m".
I am not sure how useful this is to anyone else, but it does show the technique for validating number ranges (see the first component), and besides, it uses up day 43 of one-blog-per-day-until-Xmas :)
:) Matt