[英]What regex should I use to check a string only has numbers and 2 special characters ( - and , ) in Java?
Scenario : I want to check whether string contains only numbers and 2 predefined special characters, a dash and a comma. 场景 :我要检查字符串是否仅包含数字和2个预定义的特殊字符,破折号和逗号。
My string contains numbers (0 to 9) and 2 special characters: a dash ( -
) defines a range and a comma ( ,
) defines a sequence. 我的字符串包含数字(0到9)和2个特殊字符:破折号( -
)定义范围,逗号( ,
)定义序列。
Tried attempt : Tried following regex [0-9+-,]+
, but not working as expected. 尝试过的尝试 :尝试过正则表达式[0-9+-,]+
,但未按预期工作。
Possible inputs : 可能的输入:
1-5
1,5
1-5,6
1,3,5-10
1-5,6-10
1,3,5-7,8,10
The regex should not accept these types of strings: 正则表达式不应接受以下类型的字符串:
-----
1--4
,1,5
5,6,
5,4,-
5,6-
-5,6
Please can any one help me to create regex for above scenario? 请问有人可以帮助我为上述情况创建正则表达式吗?
You may use 您可以使用
^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$
See the regex demo 见正则表达式演示
Regex details : 正则表达式详细信息 :
^
- start of string ^
-字符串的开头 \\d+
- 1 or more digits \\d+
-1个或更多数字 (?:-\\d+)?
- an optional sequence of -
and 1+ digits -可选的-
和1+数字序列 (?:,\\d+(?:-\\d+)?)*
- zero or more seuqences of: (?:,\\d+(?:-\\d+)?)*
-以下项的零个或多个出现
,
- a comma ,
-逗号 \\d+(?:-\\d+)?
- same pattern as described above -与上述相同的模式 $
- end of string. $
-字符串结尾。 Change your regex [0-9+-,]+ to [0-9,-]+ 将您的正则表达式[0-9 +-,] +更改为[0-9,-] +
final String patternStr = "[0-9,-]+";
final Pattern p = Pattern.compile(patternStr);
String data = "1,3,5-7,8,10";
final Matcher m = p.matcher(data);
if (m.matches()) {
System.out.println("SUCCESS");
}else{
System.out.println("ERROR");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.