Regular Expression to match dates in YYYY-MM-DD format

允我心安 提交于 2020-01-07 06:56:58

问题


I have a regular expression in PHP that looks for the date in the format of YYYY-MM-DD

What I have is: [\d]{4}-[\d]{2}-[\d]{2}

I'm using preg_match to test the date, the problem is that 2009-11-10 works, but 2009-11-1033434 works as well. It's been awhile since I've done regex, how do I ensure that it stops at the correct spot? I've tried doing /([\d]{4}-[\d]{2}-[\d]{2}){1}/, but it returns the same result.

Any help would be greatly appreciated.


回答1:


What you need is anchors, specifically ^ and $. The former matches the beginning of the string, the latter matches the end.

The other point I would make is the [] are unnecessary. \d retains its meaning outside of character ranges.

So your regex should look like this: /^\d{4}-\d{2}-\d{2}$/.




回答2:


How do you expect your date to be terminated ?

If an end-of-line, then a following $ should do the trick.

If by a non-digit character, then a following negative assertion (?!\d) will similarly work.




回答3:


^20[0-2][0-9]-((0[1-9])|(1[0-2]))-([0-2][1-9]|3[0-1])$

I added a little extra check to help with the issue of MM and DD getting mixed up by the user. This doesn't catch all date mixups, but does keeps the YYYY part between 2000 and 2029, the MM between 01 and 12 and the DD between 01 and 31




回答4:


you're probably wanting to put anchors on the expression. i.e.

^[\d]{4}-[\d]{2}-[\d]{2}$

note the caret and dollar sign.




回答5:


[\d]{4}-[\d]{2}-[\d]{2}?

where the question mark means "non-greedy"




回答6:


You probably want look ahead assertions (assuming your engine supports them, php/preg/pcre does)

Look ahead assertions (or positive assertions) allow you to say "and it should be followed by X, but X shouldn't be a part of the match). Try the following syntax

\d{4}-\d{2}-\d{2}(?=[^0-9])

The assertion is this part

(?=[^0-9])

It's saying "after my regex, the next character can't be a number"

If that doesn't get you what you want/need, post an example of your input and your PHP code that's not working. Those two items can he hugely useful in debugging these kinds of problems.




回答7:


You could try putting both a '^' and a '$' symbol at the start and end of your expression:

/^[\d]{4}-[\d]{2}-[\d]{2}$/

which match the start and the end of the string respectively.



来源:https://stackoverflow.com/questions/1711727/regular-expression-to-match-dates-in-yyyy-mm-dd-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!