Thursday, May 31, 2012

Regex for Month Number

This is the regular expressions pattern I use to test whether string characters represent a month number (from 01 to 12):

(0[1-9]|1[0-2])

The expression part inside the brackets is broken into 2 possible parts divided by a vertical bar (or pipe symbol): 0[1-9] or 1[0-2].

If a string matches any of the 2 parts it is true.

The first one says that the 2-character string has to start with 0 and end with any number in the range from 1 to 9, e.g. 01, 02, 09

The second part matches any 2-character string that starts with 1 and ends with 0, 1 or 2, i.e. 10, 11, or 12