Regex Specific Date Format

荒凉一梦 提交于 2019-12-11 09:17:01

问题


I was wondering if somebody could point me to a regex code that validates for this: ####/##/##

Example: 1990/05/25

The second number 0 can only be 0 or 1 and the number 2 and only be 0, 1, 2, or 3. Other than that all other numbers in this set are allowed (0-9).

The code should validate that there is only 9 or 10 characters in total including the slashes.


回答1:


If you only want to validate this format, you can use a regex like...

^\d{1,4}\/[01]?\d\/[0-3]\d$

I tested it a bit on some dates here.

This will match:

1990/01/01
2012/13/34
2013/1/39
9999/0/00

But reject:

23121/32/44
12/05/013
013/000/00

If you want to reject invalid dates as well such as 2013/02/29, you can check out this thread.




回答2:


Try this (edit following Jerry)

[0-2][0-9]{3,3}/[0|1][0-9]/[0-3][0-9]

Mess about with the {a,b} notation to change the length of the general digits, it means between a and b of the preceding expression inclusive. It's unclear in your question where you want the digit flexibility to be.

E.g. to emit 2013/5/29, use

 [0-2][0-9]{3,3}/[0|1]{0,1}[0-9]/[0-3][0-9]



回答3:


For all things regex I have found this website to be an invaluable resource. http://www.regular-expressions.info/reference.html

Specifically this page should get you what you need and contains a full explanation of how to go about validating date input format (not value) via Regular Expressions.

http://www.regular-expressions.info/dates.html

^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$

would match

yyyy-mm-dd


来源:https://stackoverflow.com/questions/16814871/regex-specific-date-format

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