Comma Separated Integer

What is the best regular expression for integers separated by a comma? It can also contain a space between the commas, and the field is not required, which means that it can be empty.

123,98549 43446 

etc..

+3
regex
source share
4 answers

This is a very simple option that suits you:

 /^[\d\s,]*$/ 

It will match any line if it contains only numbers, spaces and commas. This means that β€œ123,456” will pass, but I do not know if this was a problem.

 /^\s*(\d+(\s*,\s*\d+)*)?\s*$/ 

It has the following 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 abcd 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 
+7
source share

Assuming you need a list of integers: (\d+)

Comma and spaces should not be a problem, since you only need to iterate over the groups.

+2
source share

I do not know what you mean with the field

not required, which means that it can be empty

Also, I think this will work

 /^((\b)*[0-9]+(\b)*[,])*(\b)*[0-9]+(\b)$/ 
0
source share

This question should be more precise: for example, do you accept spaces between numbers? do you take a comma at the beginning / end? do you take the space before the decimal point? do you accept multiple consecutive spaces? do you accept spaces at start / end?

I assume that I consider it most likely that you do not accept spaces between numbers, you do not accept a comma at the beginning and end, but you accept a space before and after a comma, you accept several consecutive spaces and you accept spaces at the beginning / end.

 /^ *([0-9]+( *, *[0-9]+)*)? *$/ 
  • "": true
  • "": true
  • "123": true
  • "123.45": true
  • "123, 45, 67": true
  • "123": true
  • "1 2 3": false
  • ", 45": false
  • "123,": false

The key to writing a regular expression to match the list of "E" elements, separated by the separator "S", is that you will have to write "E" twice (here it's just "[0-9] +").

  • Template E principle (SE) *
  • E - "[0-9] +": just a sequence of numbers
  • S is "*, *" (note the spaces): a comma with optional spaces before and after

at this point we have:

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

we improve it a bit, so it also accepts spaces at the beginning / end, spaces and empty lines:

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

Note. I personally prefer to use [0-9] instead of \ d, I think it is less confusing to read.

0
source share

All Articles