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?
开发者_JAVA技巧Thank you very much.
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.
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.
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)
精彩评论