我需要一个正则表达式来判断字符串是否采用以下格式。数字组必须用逗号分隔。可以包含一系列由 - 分隔的数字
300, 200-400, 1, 250-300
这些组可以按任何顺序排列。
这是我到目前为止所拥有的,但它与整个字符串不匹配。它只匹配数字组。
([0-9]{1,3}-?){1,2},?
我需要一个正则表达式来判断字符串是否采用以下格式。数字组必须用逗号分隔。可以包含一系列由 - 分隔的数字
300, 200-400, 1, 250-300
这些组可以按任何顺序排列。
这是我到目前为止所拥有的,但它与整个字符串不匹配。它只匹配数字组。
([0-9]{1,3}-?){1,2},?
试试这个:
^(?:\d{1,3}(?:-\d{1,3})?)(?:,\s*\d{1,3}(?:-\d{1,3})?|$)+
由于您没有指定数字范围,因此我将其留给您。无论如何,您都应该使用正则表达式进行数学运算:)
解释:
"
^ # Assert position at the beginning of the string
(?: # Match the regular expression below
\\d # Match a single digit 0..9
{1,3} # Between one and 3 times, as many times as possible, giving back as needed (greedy)
(?: # Match the regular expression below
- # Match the character “-” literally
\\d # Match a single digit 0..9
{1,3} # Between one and 3 times, as many times as possible, giving back as needed (greedy)
)? # Between zero and one times, as many times as possible, giving back as needed (greedy)
)
(?: # Match the regular expression below
# Match either the regular expression below (attempting the next alternative only if this one fails)
, # Match the character “,” literally
\\s # Match a single character that is a “whitespace character” (spaces, tabs, and line breaks)
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\\d # Match a single digit 0..9
{1,3} # Between one and 3 times, as many times as possible, giving back as needed (greedy)
(?: # Match the regular expression below
- # Match the character “-” literally
\\d # Match a single digit 0..9
{1,3} # Between one and 3 times, as many times as possible, giving back as needed (greedy)
)? # 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)
\$ # Assert position at the end of the string (or before the line break at the end of the string, if any)
)+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
"
^(\d+(-\d+)?)(,\s*(\d+(-\d+)?))*$
这应该有效:
/^([0-9]{1,3}(-[0-9]{1,3})?)(,\s?([0-9]{1,3}(-[0-9]{1,3})?))*$/
你需要一些重复:
(?:([0-9]{1,3}-?){1,2},?)+
为确保数字正确,即您不匹配 010 之类的数字,您可能需要稍微更改正则表达式。我还更改了正则表达式的范围部分,以便您不匹配 100-200- 之类的内容,而只匹配 100 或 100-200,并在逗号后添加了对空格的支持(可选):
(?:(([1-9]{1}[0-9]{0,2})(-[1-9]{1}[0-9]{0,2})?){1,2},?\s*)+
此外,根据您要捕获的内容,您可能希望将捕获括号()
更改为非捕获括号(?:)
更新
基于最新评论的修订版:
^\s*(?:(([1-9][0-9]{0,2})(-[1-9][0-9]{0,2})?)(?:,\s*|$))+$
([0-9-]+),\s([0-9-]+),\s([0-9-]+),\s([0-9-]+)
试试这个正则表达式
^(([0-9]{1,3}-?){1,2},?\s*)+$