正则表达式日期匹配不起作用
我的正则表达式有问题。这里是。
/0[1-9]|1[0-2]|^[1-9]{1}$\/^[1-9]{1}$|0[1-9]|[1-2]\d|3[0-1]\/19\d{2}|20\d{2}/
它不应该匹配这个日期,
1/32/2006
但由于某种原因它匹配,你能告诉我我做错了什么吗?
I have a problem with my regex. Here it is.
/0[1-9]|1[0-2]|^[1-9]{1}$\/^[1-9]{1}$|0[1-9]|[1-2]\d|3[0-1]\/19\d{2}|20\d{2}/
It should not match this date,
1/32/2006
but for some reason it is matching, can you tell me what I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你似乎有几个问题。
正则表达式与您列出的第一个替代方案“0[1-9]”匹配“06”(来自 2006 年),
您可能是指
或类似的内容(我没有测试该正则表达式,它可能还存在其他问题),但你真的应该看看 正则表达式来匹配有效的日期中的一天 查看更好的正则表达式,并告诉明智的人如何在正则表达式中执行此类操作。
You would seem to have several problems.
The regex is matching "06" (from 2006) in the very first alternative you have listed "0[1-9]"
You probably meant
or something like that (I have not tested that regex and it probably has other problems remaining), but you should really look at Regular Expression to match a valid day in a date to see a better regexp and words to the wise about doing stuff like this in a regex.
这很有趣:
看起来您正在使用它来匹配前面或后面没有其他数字的数字。那是行不通的。
^
和$
将匹配锚定到字符串的开头和结尾,而{1}
则不执行任何操作。如果您想允许使用带有可选前导零的单位数字,请使用以下内容:
完整的正则表达式将是:
我还添加了用于分组的括号,正如 @Seth 建议的那样。
This is interesting:
It looks like you're using that to match a digit that's not preceded or followed by another digit. That won't work.
^
and$
anchor the match to the beginning and end of the string, and{1}
does nothing at all.If you want to allow for a single-digit number with an optional leading zero, use this:
The full regex would then be:
I've also added parentheses for grouping, as @Seth suggested.
您需要对这些部分进行分组并去掉
^
和$
。You need to group the sections and get rid of the
^
and$
.即使使用所有间距和更好的分隔符,
其可读性也不像
我应用的一些修复那样:
\d
不等于[0-9]
。$
允许换行。Even with all the spacing and the better delimiter,
is not nearly as readable as
I've applied some fixes:
\d
is not equivalent to[0-9]
.$
allows for a newline.此处对匹配日期的正则表达式进行了很好的概述。特别是,它列出了用于匹配 MM/DD/YYYY 日期的正则表达式:
There is a good overview of regular expressions matching dates here. In particular, it lists this regular expression for matching MM/DD/YYYY dates: