Need a Regex for comma separated number list

北慕城南 提交于 2019-12-04 18:34:13

the range operator is there only to specify range of ASCII chars, not numbers. Try this instead:

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

Your regexp is wrong: It says "from the beginning of the string, match one or more groups such that the group is made of digits 0 to 9 (other 9 is redundant), maybe followed by comma. Up to the end".

This is clearly not what you want. You need this:

^\d+(?:,\d+)*$

It matches: "from the beginning of the string match at one or more digits, optionally followed by groups consisting of comma followed by one or more digits, up to the end of the string". The groups are non-capturing one, so you can have at most one match.

^(([0-9],?)+)$ or ^([0-9],?)+$/ depending on reuse

Test

my %a=qw(1,2,444,5,  Pass
1,2,444,5  Pass
,1,2,444,5, Fail
,1,2,444,5  Fail
1,,2,444,5  Fail
1,,2,444,5,, Fail
);

while(my ($k,$v)=each(%a)) {
    $vv = ($k =~ m/^(([0-9],?)+)$/) ? "Pass" : "Fail";
    print "$k $v $vv\n";
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!