简体   繁体   English

使用正则表达式匹配日期和时间

[英]Matching date and time using regex

I am trying to write a regex that matches the date and time in this format - d/m/YH:m am/pm.我正在尝试以这种格式编写与日期和时间匹配的正则表达式 - d/m/YH:m am/pm。 For example, 1/2/2020 1.30pm例如,2020 年 1 月 2 日1/2/2020 1.30pm

This is the regex I am using but it does not match the date and time specified in the example -这是我正在使用的正则表达式,但它与示例中指定的日期和时间不匹配 -

$value = '1/2/2020 1.30pm';
if(preg_match("/^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4} (0\d|1[0-2]):([0-5]\d)(?::((?2)))?\h*([ap]m)? $/", $value) === 0) {
     return false;
}else{
     return true;
}

Please kindly help correct my mistakes on the regex expression请帮助纠正我在正则表达式上的错误

As others have pointed out, there are lots of ways to validate the date, in addition to matching;正如其他人所指出的,除了匹配之外,还有很多方法可以验证日期; you could find some different approaches.你可以找到一些不同的方法。 Here is a regex that will match your date, regardless of what you use to separate the numbers.这是一个与您的日期匹配的正则表达式,无论您使用什么来分隔数字。 \W indicates any "non-word character" will match -, or / or anything so long as it isn't a letter, digit or underscore. \W 表示任何“非单词字符”都将匹配 - 或 / 或任何内容,只要它不是字母、数字或下划线即可。 The?这? will match 0 or 1, and the * will match zero or more.将匹配 0 或 1,而 * 将匹配零个或多个。

^\d+\W\d+\W\d+\s+\d+\W?\d+\w*

Will match all of these:将匹配所有这些:

01/02/2020 11:45am

01-02-2020 10.33pm

1-23-68 2345

09/30/2323 23:15

Cheers!干杯! Kylie凯莉

If you don't care about some freedom in the format (like accepting both pm and PM ), you can use DateTime::createFromFormat() :如果您不关心格式的某些自由度(例如同时接受pmPM ),您可以使用DateTime::createFromFormat()

$dateTime = DateTime::createFromFormat('j/n/Y g.ia', $value);
$isValid = $dateTime !== false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM