[Tutor] Amazing power of Regular Expressions...

Kent Johnson kent37 at tds.net
Sun Nov 5 16:02:56 CET 2006


Alan Gauld wrote:
> But I sure agree with it. The problem with Regex is that they can
> be just a bit too powerful. To cite another programming proverb,
> this time by Bjarne Stroustrup I think:
> 
> "C makes it easy to shoot yourself in the foot;
> C++ makes it  harder, but when you do,
> it blows away your whole leg."
> 
> Regex can be like that too.

I guess it's time to trot out the famous quote of Jamie Zawinsky:

> Some people, when confronted with a problem, think
> “I know, I'll use regular expressions.”   Now they have two problems.

In this case I think regex is not the best solution. A better way to 
validate a date is to try to use it as a date. The regex 
'\d\d/\d\d/\d\d\d\d' accepts all kinds of non-dates such as 99/99/9999, 
not to mention accepting US format dates such as 12/25/2006 when you 
want 25/12/2006. I would use
   import time
   try:
     time.strptime(date, '%d/%m/%Y')
     # it's a valid date
   except ValueError:
     # not a valid date

which at least restricts the input to something that is a valid date, 
though it won't detect that a user typed 11/5/2006 when they mean 5/11/2006.

Regular expressions are an extremely powerful and useful tool that every 
programmer should master and then put away and not use when there is an 
alternative :-)

Kent



More information about the Tutor mailing list