syntax-check with regular expressions?

Matteo Dell'Amico della at toglimi.linux.it
Tue Jul 27 08:16:25 EDT 2004


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. :-)

-- 
Ciao,
Matteo



More information about the Python-list mailing list