Javascript date regex DD/MM/YYYY

题意:JavaScript 日期正则表达式 DD/MM/YYYY。

问题背景:

I know there are a lot of regex threads out there by I need a specific pattern I couldn't fin anywhere

我知道网上有很多正则表达式的帖子,但我需要一个特定的模式,我在任何地方都找不到。

This regex validates in a YYYY-MM-DD format

这个正则表达式验证的是 YYYY-MM-DD 格式。

/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/

I need the pattern to be DD/MM/YYYY (day first since it's in spanish and only "/", "-" should not be allowed)

我需要模式为 DD/MM/YYYY(日期在前,因为它是西班牙语,并且只允许使用 "/",不允许使用 "-")。

I searched several regex libraries and I think this one should work... but since I'm not familiar with regex I'm not sure it validates like that

我搜索了几个正则表达式库,我认为这个应该有效……但由于我对正则表达式不太熟悉,所以不确定它是否能这样验证。

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

I also don't know ho to escape the slashes, I try to "see" the logic in the string but it's like trying "see" the Matrix code for me. I'm placing the regex string in a options .js

我也不知道如何转义斜杠,我试图在字符串中“看懂”逻辑,但对我来说就像在“看”矩阵代码。我将正则表达式字符串放在 options.js 中。

[...]  },
"date": {
                    "regex": (0[1-9]|[12][0-9]|3[01])[ \.-](0[1-9]|1[012])[ \.-](19|20|)\d\d,
                    "alertText": "Alert text AAAA-MM-DD"
                },
"other type..."[...]

So, if the regex is ok, how would I escape it? if it's not, what's the correct regex and how do I escape it? :P

所以,如果正则表达式是正确的,我该如何转义它?如果不正确,正确的正则表达式是什么,以及我该如何转义它?:P

Thanks a lot

问题解决:

You could take the regex that validates YYYY/MM/DD and flip it around to get what you need for DD/MM/YYYY:

你可以获取验证 YYYY/MM/DD 的正则表达式,然后反转它,以得到你需要的 DD/MM/YYYY:

/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/

BTW - this regex validates for either DD/MM/YYYY or DD-MM-YYYY

顺便提一下,这个正则表达式验证的是 DD/MM/YYYY 或 DD-MM-YYYY。

P.S. This will allow dates such as 31/02/4899

P.S. 这将允许像 31/02/4899 这样的日期。

猜你喜欢

转载自blog.csdn.net/suiusoar/article/details/143445487