从任何字符串获取日期yyyy-mm-dd的正则表达式 [英] regex to get date yyyy-mm-dd from any string

查看:181
本文介绍了从任何字符串获取日期yyyy-mm-dd的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,请原谅我没有正则表达式熟悉那么多,我想要的是一个正则表达式,将从任何类型的字符串中提取一个像mysql日期的日期。
到目前为止,我使用的是: ^ [0-9] {4} - (0 [1-9] | 1 [0-2]) - (0 [1-9] | [1-2] [0-9] | 3 [0-1])$ ​​



不过现在我想提取日期模式从其他字符串和datetime字符串我尝试将正则表达式更改为 ^ [0-9] {4} - (0 [1-9] | 1 [0-2]) - (0 [1-9 ] | [1-2] [0-9] | 3 [0-1])。基于一些在线正则表达式测试人员,但它失败。还有一段时间,它给了我一个3位数字的结果。



换句话说,sting从...开始, yyyy-mm-dd 后跟空格字符数字或任何东西。如何提取日期?



更新



我正在测试正则表达式在这里使用preg_match: http://www.pagecolumn.com/tool/pregtest.htm



到目前为止,唯一似乎有效的是

  0-9] {4}  - (0 [1-9] | 1 [0-2]) - (0 [1-9] | [1-2] [0-9] | 3 [0-1]) 


解决方案

要匹配出现的日期,请删除 $ ^ 从您的原始正则表达式锚定。



匹配任何输入开始的日期会在末尾删除 $ (留下 ^ )。



为方便起见,您也可以将余下的模式放在括号内,以便整个匹配也被捕获。



您的建议改进在末尾有一个虚假点,与任何角色匹配;这就是以三位数的日期返回比赛的原因。


first of all excuse me for not being regex familiar that much.What I Would like is a regex that will extract a date like mysql date from any type of string. Until now I was using this : ^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$

However now I want to extract date patterns from other strings and datetime strings I tried altering the regex to ^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]). based on some online regex testers, but it fails. Also some times it gave me a result with a 3 digit day.

In other words sting starts with, yyyy-mm-dd and is followed up by spaces characters numbers or anything. How do I extract the date?

UPDATE

I'm testing regex with preg_match here: http://www.pagecolumn.com/tool/pregtest.htm

so far the only thing that seems to work is

[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])

解决方案

To match dates wherever they appear, remove the $ and ^ anchors from your original regex.

To match dates at the start of any input remove the $ at the end (leave the ^).

You can also put the remaining pattern inside parentheses for convenience, so that the match is also captured as a whole.

Your suggested improvement has a spurious dot at the end which will match any character; that was the reason for returning matches with three-digit days.

这篇关于从任何字符串获取日期yyyy-mm-dd的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆