473,404 Members | 2,179 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

syntax-check with regular expressions?

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
Jul 18 '05 #1
5 2263
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
Jul 18 '05 #2
sp******@gmx.de (Detlef Jockheck) wrote in
news:b5**************************@posting.google.c om:
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

Don't use a regexp for this sort of task, its much better to do the
conversion and catch an error if the conversion fails. In this case you
should use time.strptime with an appropriate format. Sample code as
requested:
import time
time.strptime("27.7.2004","%d.%m.%Y") (2004, 7, 27, 0, 0, 0, 1, 209, -1) time.strptime("27.13.2004","%d.%m.%Y")
Traceback (most recent call last):
File "<pyshell#8>", line 1, in -toplevel-
time.strptime("27.13.2004","%d.%m.%Y")
File "C:\Python23\lib\_strptime.py", line 424, in strptime
raise ValueError("time data did not match format: data=%s fmt=%s" %
ValueError: time data did not match format: data=27.13.2004 fmt=%d.%m.%Y time.strptime("29.2.1800", "%d.%m.%Y")
Traceback (most recent call last):
File "<pyshell#15>", line 1, in -toplevel-
time.strptime("29.2.1800", "%d.%m.%Y")
File "C:\Python23\lib\_strptime.py", line 513, in strptime
julian = datetime_date(year, month, day).toordinal() - \
ValueError: day is out of range for month time.strptime("29.2.2000", "%d.%m.%Y") (2000, 2, 29, 0, 0, 0, 1, 60, -1)


Jul 18 '05 #3


Use time.strptime and it'll check everything for you.
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. :-)


Jul 18 '05 #4
Le 27-07-2004, Duncan Booth <me@privacy.net> a écrit*:
Don't use a regexp for this sort of task, its much better to do the
conversion and catch an error if the conversion fails. In this case you
should use time.strptime with an appropriate format. Sample code as
requested:


Just as a side note, be careful with strptime, if you have cross
platform portability in mind. On older versions of python, this function
is not available on Windows, and on Unix systems, it relies on the C
library which is not always the GNU libc, which means that some
extensions available on linux systems are not available on Unix boxes.
We had the case on project which was deployed on AIX, and had to fight
with IBM's strptime implementation regarding white space handling. I
think it used to be picky with leading zeros too.

--
Alexandre Fayolle
Logilab
Jul 18 '05 #5
Matteo Dell'Amico <de***@toglimi.linux.it> wrote in message news:<tI********************@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
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Ken in Melbourne Australia | last post by:
If I use the curly bracket syntax (referred to as the complex syntax) within a string, how do I get to call a function within it? The php manual says that the first (or previous) character for...
699
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro...
14
by: Sandy Norton | last post by:
If we are going to be stuck with @decorators for 2.4, then how about using blocks and indentation to elminate repetition and increase readability: Example 1 --------- class Klass: def...
16
by: George Sakkis | last post by:
I'm sure there must have been a past thread about this topic but I don't know how to find it: How about extending the "for <X> in" syntax so that X can include default arguments ? This would be very...
19
by: Nicolas Fleury | last post by:
Hi everyone, I would to know what do you think of this PEP. Any comment welcomed (even about English mistakes). PEP: XXX Title: Specialization Syntax Version: $Revision: 1.10 $...
4
by: Jeremy Yallop | last post by:
Looking over some code I came across a line like this if isalnum((unsigned char)c) { which was accepted by the compiler without complaint. Should the compiler have issued a diagnostic in this...
177
by: C# Learner | last post by:
Why is C syntax so uneasy on the eye? In its day, was it _really_ designed by snobby programmers to scare away potential "n00bs"? If so, and after 50+ years of programming research, why are...
2
by: bor_kev | last post by:
Hi, First of all, i want to use the new managed class syntax and STL.NET under Microsoft Visual (C++) Studio 2005 Beta. I read in a Microsoft...
3
by: Manuel | last post by:
I'm trying to compile glut 3.7.6 (dowbloaded from official site)using devc++. So I've imported the glut32.dsp into devc++, included manually some headers, and start to compile. It return a very...
2
by: glomde | last post by:
Hi I would like to extend python so that you could create hiercical tree structures (XML, HTML etc) easier and that resulting code would be more readable. The syntax i would like is something...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.