我正在尝试构建一个正则表达式来检查一个字符串是否有 0 次或 1 次连字符。
所以它会返回以下字符串。
1-5
1,3-5
1,3
以下是错误的。
1-3-5
我已经尝试了以下方法,但是 1-3-5 没问题:
([^-]?-){0,1}[^-]
最佳答案
这个有效:
^[^-]*-?[^-]*$
^^ ^ ^ ^
|| | | |
|| | | |-- Match the end of string
|| | |------- Match zero or more non-hyphen characters
|| |--------- Match zero or one hyphens
||-------------- Match zero or more non-hyphen characters
|--------------- Match the beginning of string
在这种情况下,您需要指定匹配输入字符串的开头(^
)和结尾($
),这样您就不会得到多个匹配对于像 1-3-5
这样的字符串。
关于c# - 正则表达式匹配字符串中的连字符 0 次或 1 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17153032/