年份序列的正则表达式
所以我试图匹配类似
2011,2012,2013
或
2011,
或
2011
但不是:
2011,201
或 2011,201,2012
我尝试使用 ([0-9]{ 4},?([0-9]{4},?)*)
但如果第一年匹配,则不会考虑其余年份。
So I'm trying to match something like
2011,2012,2013
or
2011,
or
2011
but NOT:
2011,201
or 2011,201,2012
I tried with ([0-9]{4},?([0-9]{4},?)*)
but if the first year is matched, it does not consider the rest .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你很接近。
这将匹配由 4 位数字和逗号的重复序列组成的任何字符串。
^
和$
分别匹配字符串的开头和结尾。因此,仅当字符串仅由这些元素组成时,它才会匹配。(?:)
是非捕获组。它允许您创建重复组,而无需将所有组存储到变量中。编辑:忘记了末尾的可选逗号。添加了
,?
来处理它。编辑2:根据FailedDev的建议,这是我最初的想法。它也有效,但我认为它更难理解。它更聪明,但这并不总是一件好事。
You were close.
That will match any string consisting of a repeating sequence of 4-digit numbers and commas.
The
^
and$
match the beginning and end of the string, respectively. Thus, it will only match if the string consists of only those elements.The
(?:)
is a non-capture group. It allows you to create repeating groups without storing all of them into variables.EDIT: Forgot about the optional comma at the end. Added a
,?
to take care of it.EDIT 2: At FailedDev's advice, here was my original idea. It also works, but I think it is harder to understand. It is more clever, but that's not always a good thing.
这应该有效。
说明:
This should work.
Explanation :
这样就可以解决问题了...
即 4 位数字后跟零个或多个(逗号后跟 4 位数字),并且可以选择在结尾之前加上最后一个(难看的)逗号。
第一个
^
和最后一个$
字符确保字符串中不能出现任何其他内容。This will do the trick...
i.e. 4 digits followed by zero or more of (a comma followed by 4 digits) and optionally a last (bad looking) comma before the end.
The first
^
and last$
chars ensure that nothing else can be present in the string.检查四位数字,每个数字可能后跟一个逗号,0 到多次
Checks for four digits, each possibly followed by a comma, 0 to many times