java 正则表达式匹配连字符和逗号,并且仅在两者之间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11919374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:56:23  来源:igfitidea点击:

Regex matching hyphen and comma and only in between

javaregex

提问by FirmView

I am checking for a string using regex.

我正在使用正则表达式检查字符串。

The rule is :

规则是:

The String can,

字符串可以,

contain any digits, hyphen and comma

包含任何数字、连字符和逗号

Hyphen and Comma should be only in-between the digits. It should not in the beginning or the end of the string.

连字符和逗号应仅位于数字之间。它不应位于字符串的开头或结尾。

Comma is optional. Hyphen is compulsory

逗号是可选的。连字符是强制性的

For Example,

例如,

Valid :

有效的 :

10-20
10-20-3
10-20,3 

InValid :

无效的 :

10
-10
,10
10-20,
10-20-
10,20

The code I tried so far:

到目前为止我尝试过的代码:

[0-9,-]+ 

can someone suggest how to check the coma and hyphen should not be in the beginning or end of the string and also the above conditions?

有人可以建议如何检查昏迷和连字符不应在字符串的开头或结尾以及上述条件吗?

回答by dasblinkenlight

Try this expression:

试试这个表达:

[0-9][0-9,-]*-[0-9,-]*[0-9]

What this means is that the string must:

这意味着字符串必须:

  • Starts and ends in a digit
  • Contains at least one dash in the middle
  • after the first digit and before the dash there's zero or more [0-9,-]characters
  • between the dash and the last digit there's zero or more [0-9,-]characters
  • 以数字开头和结尾
  • 中间至少包含一个破折号
  • 在第一个数字之后和破折号之前有零个或多个[0-9,-]字符
  • 在破折号和最后一位数字之间有零个或多个[0-9,-]字符

回答by John Corbett

you should try this

你应该试试这个

[0-9][0-9,\-]*-[0-9,\-]*[0-9]

I think the hyphen needs to be backslashed in the character class

我认为连字符需要在字符类中反斜杠

回答by vusan

The expression should include ^or \Aat the beginning and $or \zat end otherwise the expression would also match the invalid string like:

表达式应该在开头和/或结尾包含^\A,否则表达式也将匹配无效字符串,例如:$\z

,10
20-
-34

So the expression should be :

所以表达式应该是:

^[0-9][0-9,-]*-[0-9,-]*[0-9]$