Regular expression for checking date

Hi, I wrote a regular expression to check where a string is of type char - or. or / or: or AM or PM or a space. Regex follworig is used for this, but I want to make case fail if the string contains char, except for AMP. import re

Datere = re.compile("[-./\:?AMP ]+")

FD = { 'Date' : lambda date : bool(re.search(Datere,date)),}

def Validate(date):

    for k,v in date.iteritems():
        print k,v
        print FD.get(k)(v)

Conclusion:

Validate({'Date':'12/12/2010'})
Date 12/12/2010
True
Validate({'Date':'12/12/2010 12:30 AM'})
Date 12/12/2010
True

Validate({'Date':'12/12/2010 ZZ'})
Date 12/12/2010
True  (Expecting False)

Edited: Check ({'Date': '12122010'}) Date 12122010 False (Waiting False)

How can I find a string other than char APM, any suggestion. Many thanks.

+5
source share
4 answers

Try:

^[-./\:?AMP \d]*$

Regex Changes

  • It is bound to ^ and $, which means that the whole string must match, not partially
  • \ d is added to the character class to allow digits

, 1

, , * +

+1

, :

^[-0-9./:AMP ]+$

^ $ , , ( $).

+1

, , , , '-30/A-MP/2012/12', '-30/A-MP/20PA12/12'.

, :

import datetime
date = '12-12-2012 10:45 AM'
formats = ("%d-%m-%Y %I:%M %p", "%d/%m/%Y %I:%M %p", ...)
for fmt in formats:
    try:
        valid_date = datetime.datetime.strptime(date, fmt)
    except ValueError as e:
        print(e)

, datetime ( , ), , . : http://docs.python.org/library/time.html#time.strftime

+1

- , .

import re
Datere = re.compile("""
    ^(?:\d\d[-./\:]){2} ## dd_SEP_dd
    \d{4}\s* ## year may be followed by  spaces
    (?:\d\d[-./\:]\d\d\s+(?:AM|PM))? ## hh_SEP_mm spaces followed by AM/PM and this is optional
    \s*$""",re.X)

FD = { 'Date' : lambda date : bool(re.search(Datere,date)),}

def Validate(date):

    for k,v in date.iteritems():
        print k,v
        print FD.get(k)(v)

print Validate({'Date':'12/12/2010'})
print Validate({'Date':'12/12/2010 12:30 AM'})
print  Validate({'Date':'12/12/2010 ZZ'})
+1

All Articles