views:

43

answers:

3

Hi all,

Is there any way to write a Regex that can validate one type of delimiter in one date time string only?

For example, 30/04/2010 is correct but 30-04/2010 is incorrect.

I googled and found something about backtrack but I am not very sure how to use it. For example, if i have this regex:

(?P<date>((31(?![\.\-\/\—\ \,\–\-]{1,2}(Feb(ruary)?|Apr(il)?|June?|(Sep(?=\b|t)t?|Nov)(ember)?)))|((30|29)(?![\.\-\/\—\ \,\–\-]{1,2}Feb(ruary)?))|(29(?=[\.\-\/\—\ \,\–\-]{1,2}Feb(ruary)?[\.\-\/\—\ \,\–\-]{1,2}(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\d|2[0-8])[\.\-\/\—\ \,\–\-]{1,2}(Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\b|t)t?|Nov|Dec)(ember)?)[\.\-\/\—\ \,\–\-]{1,2}((1[6-9]|[2-9]\d)\d{2}))

Then how am I supposed to use backtrack here?

Thank you very much.

+5  A: 

Not an answer to your question, but have you considered using strtotime()?

It is a very flexible function able to parse about any english date and time:

Feb 2, 2010
February 2, 2010
02/02/10
4 weeks ago
Next Monday

If a date is unparseable, the function will return false (or -1 prior to PHP 5.1).

There are a few gotchas - I think I remember that when using xx-xx-xxxx notation, it tends to assume an european DD-MM-YYYY date - but all in all, you may fare much better with it than with a regex.

Pekka
Thank you but how about 08/2010? I tried but php failed to parse that format. Let's say we have this string 09/07-10/12. I want the regEx to match 09/07 and 10/12 as two dates. Otherwise, 09/07-10 might be mismatched as one date.
James
@James yes, it fails to parse `08/2010` (it does `August 2010` properly if that's any help.) But matching things like `09/07-10/12` without a specific ruleset will be extremely complex to achieve in a Regex. Can you add more detail about your exact situation? Can you impose some kind of a form on the input?
Pekka
A: 

The regex you have, seems to check the string is in any of the possible formats that a datetime can be. If you just want to check for your given example 30/04/2010 you could use this easy one

([\d]{1,2})\/([\d]{1,2})\/([\d]{2,4})

(day and month 1-2 digits, year 2-4 digits)

Marks
Thanks but that was just an example only.
James
+1  A: 

While answer from Pekka much better solves your problem, I think it is worth answering this part of your question:

Then how am I supposed to use backtrack here?

Here is an example of regex which matches "05-07-2010" and "05/07/2010", but not "05-07/2010":

"#^\d{2}([/-])\d{2}\1\d{4}$#"
        ------     --

The most important parts of the regex are underlined; \1 here is a back reference to the first capturing subpattern ([/-]). You can get more information in PHP Manual's Back references chapter.

Alexander Konstantinov