datetime(2008-09-01 12:35:45)的正则表达式模式是什么?

时间:2020-03-05 18:45:55  来源:igfitidea点击:

DateTime(2008-09-01 12:35:45)的RegEx模式是什么?

我收到此错误:

No ending delimiter '^' found

使用:

preg_match('(?n:^(?=\d)((?<day>31(?!(.0?[2469]|11))|30(?!.0?2)|29(?(.0?2)(?=.{3,4}(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])(?<sep>[/.-])(?<month>0?[1-9]|1[012])(?<year>(1[6-9]|[2-9]\d)\d{2})(?:(?=\x20\d)\x20|$))?(?<time>((0?[1-9]|1[012])(:[0-5]\d){0,2}(?i:\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$)', '2008-09-01 12:35:45');

给出此错误:

Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 0 in E:\www\index.php on line 19

解决方案

回答

http://regexlib.com/REDetails.aspx?regexp_id=610

^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$
This RE validates both dates and/or
  times patterns. Days in Feb. are also
  validated for Leap years. Dates: in
  dd/mm/yyyy or d/m/yy format between
  1/1/1600 - 31/12/9999. Leading zeroes
  are optional. Date separators can be
  either matching dashes(-), slashes(/)
  or periods(.) Times: in the hh:MM:ss
  AM/PM 12 hour format (12:00 AM -
  11:59:59 PM) or hh:MM:ss military time
  format (00:00:00 - 23:59:59). The 12
  hour time format: 1) may have a
  leading zero for the hour. 2) Minutes
  and seconds are optional for the 12
  hour format 3) AM or PM is required
  and case sensitive. Military time 1)
  must have a leading zero for all hours
  less than 10. 2) Minutes are
  manditory. 3) seconds are optional.
  Datetimes: combination of the above
  formats. A date first then a time
  separated by a space. ex) dd/mm/yyyy
  hh:MM:ss

编辑:确保我们从regexlib.com网站复制RegEx,因为StackOverflow有时会删除/破坏特殊字符。

回答

我们应该在http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5找到所需的内容。

回答

一个简单的版本将适用于上述格式,但不是所有其他@Espos版本:

(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})

回答

@Espo:我只需要说正则表达式是不可思议的。我讨厌不得不编写对匹配有用的代码,例如我们是否想真正找出用户键入的日期和时间。

好像汤姆的解决方案会更站不住脚,因为它是关于亿万倍简单,增加了一些括号,你可以很容易地得到在用户键入的值:

(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})

如果我们使用的是perl,则可以通过以下方式获取值:

$year = ;
$month = ;
$day = ;
$hour = ;
$minute = ;
$second = ;

其他语言将具有类似的功能。请注意,如果要接受诸如单位数月份的值,则需要对正则表达式进行一些次要的修改。

回答

PHP preg函数需要正则表达式用定界符(可以是任何字符)进行包装。我们必须先在正则表达式内转义,才能使用此定界符。这应该可以工作(此处的分隔符为/):

preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/', '2008-09-01 12:35:45');

// or this, to allow matching 0:00:00 time too.
preg_match('/\d{4}-\d{2}-\d{2} \d{1,2}:\d{2}:\d{2}/', '2008-09-01 12:35:45');

如果需要匹配仅包含日期时间的行,请在正则表达式的开头和结尾添加^和$。

preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', '2008-09-01 12:35:45');

链接到PHP手册的preg_match()