首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >年份序列的正则表达式

年份序列的正则表达式
EN

Stack Overflow用户
提问于 2011-10-27 05:32:47
回答 4查看 868关注 0票数 2

所以我试着匹配像这样的东西

代码语言:javascript
复制
2011,2012,2013

代码语言:javascript
复制
2011,

代码语言:javascript
复制
2011 

但不是:

2011,2012011,201,2012

我尝试使用([0-9]{4},?([0-9]{4},?)*),但如果第一年匹配,则不会考虑其余年份。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-10-27 05:36:36

你们已经很接近了。

代码语言:javascript
复制
 ^[0-9]{4}(?:,[0-9]{4})*,?$

它将匹配由4位数字和逗号组成的重复序列的任何字符串。

^$分别匹配字符串的开头和结尾。因此,只有当字符串只包含这些元素时,它才会匹配。

(?:)是一个非捕获组。它允许您创建重复的组,而无需将它们全部存储到变量中。

编辑:忘记了末尾的可选逗号。添加了一个,?来处理它。

编辑2:在FailedDev的建议下,这是我最初的想法。它也是有效的,但我认为它更难理解。它更聪明,但这并不总是一件好事。

代码语言:javascript
复制
^(:?[0-9]{4}(?:,|$))+$
票数 4
EN

Stack Overflow用户

发布于 2011-10-27 05:37:30

这样就行了..。

代码语言:javascript
复制
 /^[0-9]{4}(,[0-9]{4})*,?$/

也就是说,4个数字后面跟着0个或更多(一个逗号后面跟着4个数字),还有一个可选的末尾逗号(看起来不好看)。

第一个^和最后一个$字符确保字符串中不会出现任何其他字符。

票数 1
EN

Stack Overflow用户

发布于 2011-10-27 05:38:06

代码语言:javascript
复制
if (subject.match(/^\d{4}(?:,?|(?:,\d{4}))+$/)) {
    // Successful match
}

这应该是可行的。

说明:

代码语言:javascript
复制
"^" +              // Assert position at the beginning of the string
"\\d" +             // Match a single digit 0..9
   "{4}" +            // Exactly 4 times
"(?:" +            // Match the regular expression below
   "|" +              // Match either the regular expression below (attempting the next alternative only if this one fails)
      "," +              // Match the character “,” literally
         "?" +              // Between zero and one times, as many times as possible, giving back as needed (greedy)
   "|" +              // Or match regular expression number 2 below (the entire group fails if this one fails to match)
      "(?:" +            // Match the regular expression below
         "," +              // Match the character “,” literally
         "\\d" +             // Match a single digit 0..9
            "{4}" +            // Exactly 4 times
      ")" +
")+" +             // Between one and unlimited times, as many times as possible, giving back as needed (greedy)
"$"                // Assert position at the end of the string (or before the line break at the end of the string, if any)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7909200

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档