开发者

Need a Regex for comma separated number list

开发者 https://www.devze.com 2023-02-05 19:46 出处:网络
This should be simple for experienced regex writers, but I don\'t write them much, so.... I want to do input validation on a text box on a C# MVC form, possibly using javascript or jquery.

This should be simple for experienced regex writers, but I don't write them much, so....

I want to do input validation on a text box on a C# MVC form, possibly using javascript or jquery.

I want to limit the input to a list of comma-separated integers. The list must start with a number >= 0, followed by a comma and then repeat this pattern. the list may or may not end with a comma:

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

I wrote this: ^([0-99],?)+$ and tested开发者_开发问答 it at regexlib.com and it seems to work, but the tester returns 2 matches, and I'm not sure what that means. Since it fails on the Failing cases above, I assume it would be safe for simple input validation. Is there a better pattern?

Less important question: Why does it allow 444 when the range is 0-99?


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";
};
0

精彩评论

暂无评论...
验证码 换一张
取 消