Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer separated by comma

Tags:

regex

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..

like image 229
Frenchi In LA Avatar asked Sep 23 '26 04:09

Frenchi In LA


2 Answers

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
like image 94
nickf Avatar answered Sep 25 '26 16:09

nickf


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.

like image 26
Amirshk Avatar answered Sep 25 '26 18:09

Amirshk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!