Reqular Expression to validate a date

by Semicton 16. February 2010 22:12

Regular expressions treat numbers as text so you can't simply check a series of numbers and ask the expression: Is the value of 100 between a value of 0 to 255?  To understand better, follow the explanation below.

This expression validates and matches mm/dd/yyyy

(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d

Lets break this up a bit.

Why so many ()'s ?

No, these are not emoticons :) I enclose each expression in parenthesis because I am using a pipe.  The pipe is basically an OR operator but is call an option.  If I had not surrounded the expression in parenthesis, the expression would split the regular expression into two separate options. 

MONTH

0[1-9]

The first part contains the number zero.  This is telling the expression that the zero is required and the first string matches a number between 01 and 09.

1[012]

The second part shows the number one is required if the string matches 10, 11 or 12.

final expression for the month: 

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

The day expression is very similar to the month expression.

Day

The first matches the numbers 01 through 09, the second 10 through 29, and the third matches 30 or 31. Notice how each value is checked for and split by a pipe |  This does not work for leap years!

Final expression for Day:

(0[1-9]|[12][0-9]|3[01])

Year

(19|20)

The first two digits must match 19 or 20. Notice that only the match for the first two digits have an option pipe and that they are enclosed in parenthesis.

\d\d

Next I am looking for any two digits represented by \d for anyone one digit.

Final expression for year:

(19|20)\d\d

Deliminator

Finally, Each expression must have a matching Deliminator. Notice how I allow a space in the available matches.

[-  /.]

Fun!

Final Expression

Example:

(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d

will find a match for 02/12/2008.

 

Tags:

Sandbox

Powered by Semicton 1.5.0.7

Interesting Questions

How is the age of fish determined?

Answer:

One way to determine the age of a fish is by its scales, wich have growth rings just as trees do. Scales have concentric bony ridgets or "circuli," which reflect the growth patterns of the individual fish. The portion of the scale that is embedded in the skin contains clusters of these ridges 9called "annuli"); each cluster marks one year's growth.


 Refresh

Latest Downloads:

File Name Downloads
2009/12/scribd.zip 319
2009/12/BinaryClock.zip 267