简体   繁体   English

在Java中,我应该使用哪种正则表达式来检查仅包含数字和2个特殊字符(-和,)的字符串?

[英]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.

相关问题 正则表达式模式检查字符串是否没有特殊字符 - Java - Regex pattern to check if string has no special characters - Java 如果需要检查姓名字段中的特殊字符和数字或电话字段中的特殊字符和字母数字,我应该使用什么方法? - What method should I use if need to check for special characters and digits in name field or for special characters and alphanumeric in phone field? 正则表达式检查字符串是否以“+”、“-”、“=”或“@”等特殊字符开头 Java - Regex to check if a String starts with special characters like "+" , "-" , "=" or "@" Java 检查String是否仅包含特定的重复特殊字符 - Check if String has specific repetitive special characters only 仅反转句子中的字母而不是 java 中的数字或特殊字符的字符串 - Reverse a string for only the alphabets in a sentence not numbers or special characters in java 如何在java中检查字符串是否有超过2的连续特殊字符? - How to check if the string has consequitive special characters more than 2 in java? 正则表达式模式可排除字符串中的数字和特殊字符 - Regex pattern to exclude numbers and special characters in a string 使用正则表达式检查特殊字符Java - Using a regex to check for special characters java 如何检查字符串 [Java] 中的特殊字符? - How do I check for special characters in a String[Java]? 识别字符串Java中的数字和特殊字符 - To recognize the numbers and special characters in a string Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM