1

有没有办法编写一个正则表达式,它只能在一个日期时间字符串中验证一种类型的分隔符?

例如,30/04/2010 是正确的,但 30-04/2010 是不正确的。

我用谷歌搜索并找到了一些关于回溯的东西,但我不太确定如何使用它。例如,如果我有这个正则表达式:

(?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}))

那么我应该如何在这里使用回溯?

非常感谢。

4

3 回答 3

5

不是您问题的答案,但您是否考虑过使用strtotime()?

这是一个非常灵活的函数,能够解析任何英文日期和时间:

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

如果日期不可解析,函数将返回false(或-1在 PHP 5.1 之前)。

有一些陷阱——我想我记得在使用xx-xx-xxxx符号时,它倾向于假定一个欧洲DD-MM-YYYY日期——但总而言之,你可能会比使用正则表达式更好。

于 2010-07-05T10:25:17.917 回答
1

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.

于 2010-07-05T12:15:54.110 回答
0

您拥有的正则表达式似乎检查字符串是否采用日期时间可以采用的任何可能格式。如果您只想检查您给定的示例 30/04/2010,您可以使用这个简单的示例

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

(日月1-2位,年2-4位)

于 2010-07-05T10:38:27.677 回答