Skip to main content

Sharing is Caring

Go Search
Home
  

Announcing: Community Kit for SharePoint: Development Tools Edition (CKS:DEV)
Happy Holidays!
Quick Deploy in SPVSX: Part One - Background and Approach
Announcing: SPVSX – SharePoint 2010 Visual Studio Extensions
The DebugApp trick for Productive SharePoint Development: Part 1
'Ello Guvners!
Speaking at Christchurch SharePoint User Group, this Tuesday!
Blog Hiatus, OE, and The Meaning Of Life
I'm A SharePoint Server MVP
Happy Christmas and a Merry New Year
Sharing is Caring > Categories
RegEx: Handling hour/time input in 5 minute intervals

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:

  • 23h
  • 2h 5m
  • 1
  • 50m
  • 1h30

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