![](/img/trans.png)
[英]Regex to match comma separated string with no comma at the end of the line
[英]Regex to match comma separated list with no comma on the end
我需要一个.Net(C#)正则表达式来匹配逗号分隔的数字列表,如果最后一个字符有逗号,则该列表将不匹配
123,123,123,123 true - correct match
123,123,123,123, false - comma on end
123,123,123,,123 false - double comma
,123,123,123,123 false - comma at start
"" false - empty string
123 true - single value
我找到了这个正则表达式,但是当结尾有逗号时匹配^([0-9]+,?)+$
适合这种模式的正则表达式模式是什么?
编辑:为清楚起见添加了 1 个示例,正确答案适用于123
试试这个:
//This regex was provided before the question was edited to say that
//a single number is valid.
^((\d+\s*,\s*)+(\s*)(\d+))$
//In case a single number is valid
^(\d+)(\s*)(,\s*\d+)*$
以下是测试结果
123,123,123,123 match
123,123,123,123, no match
123,123,123,,123 no match
,123,123,123,123 no match
"" no match (empty string)
123 no match for the first regex, match for the second one
编辑:修改正则表达式以包括单个数字的最后一个案例,不带任何逗号。
请试试这个
没有后缀/前缀逗号: [0-9]+(,[0-9]+)*
没有前缀(可选后缀): [0-9]+(,[0-9]+)*,?
没有后缀(可选前缀): ,?[0-9]+(,[0-9])*
可选的后缀和前缀: ,?[0-9]+(,[0-9]+)*,?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.