正则表达式 - 有什么我做错了吗?

时间:2022-09-20 18:35:59

This is javascript, but a virtually identical regex is failing in PHP too, so I don't think it's language specific

这是javascript,但是几乎完全相同的正则表达式在PHP中也失败了,所以我不认为它是特定于语言的

var r = new RegExp(
    "^(:19|20)?[0-9][0-9]"            // optional 19/20 start followed by 2 numbers
    + "-"                             // a hyphen
    + "(:0?[1-9]|1[0-2])"             // optional 0 followed by 1-9, or 10, 11, 12
    + "-"                             // a hyphen
    + "(:3[01]|[12][0-9]|0?[1-9])$"   // you get the idea.
);
r.test("2008-07-01");                // == false

What on earth am I missing?

我究竟错过了什么?

2 个解决方案

#1


11  

I think your non-capturing blocks should be e.g. (?:19|20) rather than (:19|20)

我认为你的非捕获块应该是例如(?:19 | 20)而不是(:19 | 20)

#2


2  

Correct; your regular expression would actually work with "?:"

正确;你的正则表达式实际上可以用“?:”

"?" when used a prefix indicates that you're going to do something about capturing. Either not capture the block (":"), capture ahead ("="), behind ("<="), etc.

“?”当使用前缀表示你将要做一些关于捕获的事情。要么不捕获块(“:”),要么捕获(“=”),要么捕获(“<=”)等。

#1


11  

I think your non-capturing blocks should be e.g. (?:19|20) rather than (:19|20)

我认为你的非捕获块应该是例如(?:19 | 20)而不是(:19 | 20)

#2


2  

Correct; your regular expression would actually work with "?:"

正确;你的正则表达式实际上可以用“?:”

"?" when used a prefix indicates that you're going to do something about capturing. Either not capture the block (":"), capture ahead ("="), behind ("<="), etc.

“?”当使用前缀表示你将要做一些关于捕获的事情。要么不捕获块(“:”),要么捕获(“=”),要么捕获(“<=”)等。