简体   繁体   English

正则表达式匹配逗号分隔的列表,最后没有逗号

[英]Regex to match comma separated list with no comma on the end

I need a.Net (C#) Regex to match a comma separated list of numbers that will not match if there is a comma as the last character我需要一个.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

I have found this Regex but matches when there is a comma on the end ^([0-9]+,?)+$我找到了这个正则表达式,但是当结尾有逗号时匹配^([0-9]+,?)+$

What would be a Regex pattern that would fit this pattern?适合这种模式的正则表达式模式是什么?

EDIT: Added 1 example for clarity the correct answer works for 123编辑:为清楚起见添加了 1 个示例,正确答案适用于123

Try using this pattern: 尝试使用此模式:

^([0-9]+,)*[0-9]+$

You can test it here . 你可以在这里测试一下

Try this: 试试这个:

//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+)*$ 

Here are the test results 以下是测试结果

 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

See Regex doesn't give me expected result 看到Regex没有给我预期的结果

Edit: Modified the regex to include the last case of a single number without any comma. 编辑:修改正则表达式以包括单个数字的最后一个案例,不带任何逗号。

Please Try this 请试试这个

No postfix/prefix commas: [0-9]+(,[0-9]+)* 没有后缀/前缀逗号: [0-9]+(,[0-9]+)*

No prefix (optional postfix): [0-9]+(,[0-9]+)*,? 没有前缀(可选后缀): [0-9]+(,[0-9]+)*,?

No postfix (optional prefix): ,?[0-9]+(,[0-9])* 没有后缀(可选前缀): ,?[0-9]+(,[0-9])*

Optional postfix and prefix: ,?[0-9]+(,[0-9]+)*,? 可选的后缀和前缀: ,?[0-9]+(,[0-9]+)*,?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM