What's the best regular expression for integer separated by comma? It can also contain space between comma, and the field is not required which means it could be blank.
123,98549
43446
etc..
This is a very basic one that might suit you:
/^[\d\s,]*$/
It'll match any string as long as it only contains numbers, spaces and commas. It means that "123 456" will pass, but I don't know if that's a problem.
/^\s*(\d+(\s*,\s*\d+)*)?\s*$/
This one has these results:
"" true
"123" true
"123, 456" true
"123,456 , 789" true
"123 456" false
" " true
" 123 " true
", 123 ," false
Explanation:
/^\s*(\d+(\s*,\s*\d+)*)?\s*$/
1 2 3 4 5 6 7 8 9 a b c d
1. ^ Matches the start of the string
2. \s Matches a space * means any number of the previous thing
3. ( Opens a group
4. \d Matches a number. + means one or more of the previous thing
5. ( Another group
6. \s* 0 or more spaces
7. , A comma
8. \s* 0 or more spaces
9. \d+ 1 or more numbers
a. * 0 or more of the previous thing. In this case, the group starting with #5
b. ? Means 0 or 1 of the previous thing. This one is the group at #3
c. \s* 0 or more spaces
d. $ Matches the end of the string
Assuming you want a list of integers: (\d+)
The comma and whitespaces shouldn't be an issue, since you only need to go over the groups.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With