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.
Gras double
source share