[英]regular expression not containing two or more consecutive comma or hyphen and between numbers at most one hyphen
I have scenario to validate number range, it can be multiple range or single number. 我有验证数字范围的方案,它可以是多个范围或单个数字。
Ex number 1 to 10 can be written as (1-3,4,5-8,9,10) here 1-3 indicates rage (1,2,3) I have tried java regex : 例1到10的数字可以写成(1-3,4,5-8,9,10),这里1-3表示rage(1,2,3)我试过了java regex:
Pattern.matches("^[0-9][0-9,-]*,[0-9,-]*[0-9]$","11,131-132-134,45,12--10,,10");
this pattern allows consecutive hyphen and comma, 这种模式允许连续的连字符和逗号,
Valid Input 有效输入
1) 1-3,4,5-8,9,10
2) 1-3,4-5,6-10
3) 1,2,3,4,5
4) 1,2-5,6
Invalid Input 输入无效
1) ,2,3,4-10,
2) -2,3,4-10-
3) 2,3,,4-10
4) 2,3,4--10
5) 2,3,4-6-10 (Invalid range)
can someone suggest how to check the comma and hyphen should not appear two times consecutively, start and end with number, range should not repeat (4-8-10) 有人可以建议如何检查逗号和连字符不应连续出现两次,以数字开头和结尾,范围不应重复(4-8-10)
This should be the regex you want: 这应该是您想要的正则表达式:
^\\d+(-\\d+)?(,\\d+(-\\d+)?)*$
It checks for the following sequence: 它检查以下顺序:
\\\\d+
: One or more digits \\\\d+
:一位或多位数字
(-\\\\d+)?
: An optional sequence of hyphen followed by one or more digits :连字符的可选序列,后跟一个或多个数字
(,\\\\d+(-\\\\d+)?)*
: Zero or more occurrence of a comma followed by one or more digits followed by an optional sequence of hyphen followed by one or more digits (,\\\\d+(-\\\\d+)?)*
:出现零个或多个逗号,后跟一个或多个数字,然后是可选的连字符序列,然后是一个或多个数字
As the regex looks for a digit at the beginning, a string starting with hyphen or comma will not be allowed. 正则表达式会在开头查找数字,因此不允许以连字符或逗号开头的字符串。
As it looks for a digit to be immediately followed by a hyphen and comma, a string having consecutive hyphens or commas, a hyphen immediately followed by a comma or the reverse would not be allowed. 当它寻找要紧跟连字符和逗号的数字,具有连续连字符或逗号的字符串时,不允许在连字符后紧跟逗号或反向字符的连字符。
As the ?
作为
?
in (-\\\\d+)?
在
(-\\\\d+)?
allows exactly zero or one occurrence of the (-\\\\d+)
sequence, a range like 1-2-3 will not be matched. 允许
(-\\\\d+)
序列出现零个或一个,则不会匹配1-2-3之类的范围。
If you don't need to allow a single number alone, replace the *
in ^\\\\d+(-\\\\d+)?(,\\\\d+(-\\\\d+)?)*$
with +
. 如果您不需要单独允许单号,更换
*
在^\\\\d+(-\\\\d+)?(,\\\\d+(-\\\\d+)?)*$
用+
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.