syntax-check with regular expressions?

Detlef Jockheck spamnews at gmx.de
Wed Aug 4 12:21:11 CEST 2004


Matteo Dell'Amico <della at toglimi.linux.it> wrote in message news:<tIrNc.17482$OH4.411663 at twister1.libero.it>...
> Detlef Jockheck wrote:
> > Hi,
> > 
> > I would like to check if a string contains a valid date format
> > (Format: "dd.mm.yyyy") or not.
> > 
> > What is the best way to do this. regexp? At the moment it would be
> > sufficient to check for
> > [digit][digit].[digit][digit].[digit][digit][digit][digit] but a full
> > date verification (Month in range 1-12 ...) would be very nice too.
> > 
> > Sample code would help me very much.
> > 
> > regards
> > Detlef
> > 
> > PS: I'm a python newbie, so excuse this silly question
> 
> This should work, returning True for valid dates and False otherwise:
> 
> import re
> 
> _re = re.compile(r'(\d{2})\.(\d{2})\.(\d{4})$')
> def testdate(s):
>      try:
>          day, month, year = [int(x) for x in _re.match(s).groups()]
>      except AttributeError:
>          return False
>      return 1 <= day <= 31 and 1 <= month <= 12
> 
> Implementing things such as different number of days for each month and 
> leap years is left as an exercise to the reader. :-)

Hi!

That's great. Now I understand how this works. Thank you very much :-)

regards
Detlef



More information about the Python-list mailing list