所以我试着匹配像这样的东西
2011,2012,2013或
2011,或
2011 但不是:
2011,201或2011,201,2012
我尝试使用([0-9]{4},?([0-9]{4},?)*),但如果第一年匹配,则不会考虑其余年份。
发布于 2011-10-27 05:36:36
你们已经很接近了。
^[0-9]{4}(?:,[0-9]{4})*,?$它将匹配由4位数字和逗号组成的重复序列的任何字符串。
^和$分别匹配字符串的开头和结尾。因此,只有当字符串只包含这些元素时,它才会匹配。
(?:)是一个非捕获组。它允许您创建重复的组,而无需将它们全部存储到变量中。
编辑:忘记了末尾的可选逗号。添加了一个,?来处理它。
编辑2:在FailedDev的建议下,这是我最初的想法。它也是有效的,但我认为它更难理解。它更聪明,但这并不总是一件好事。
^(:?[0-9]{4}(?:,|$))+$发布于 2011-10-27 05:37:30
这样就行了..。
/^[0-9]{4}(,[0-9]{4})*,?$/也就是说,4个数字后面跟着0个或更多(一个逗号后面跟着4个数字),还有一个可选的末尾逗号(看起来不好看)。
第一个^和最后一个$字符确保字符串中不会出现任何其他字符。
发布于 2011-10-27 05:38:06
if (subject.match(/^\d{4}(?:,?|(?:,\d{4}))+$/)) {
// Successful match
}这应该是可行的。
说明:
"^" + // 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)https://stackoverflow.com/questions/7909200
复制相似问题