What's 开发者_如何学Gothe 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.
I don't know what you mean with the field
is not required which means it could be blank
Besides that, I think this sould work
/^((\b)*[0-9]+(\b)*[,])*(\b)*[0-9]+(\b)$/
This question should be more precise : for example, do you accept spaces between digits? do you accept comma at start/end? do you accept space before comma? do you accept several consecutive spaces? do you accept spaces at start/end ?
I will assume what I think is the most probable, so that you don't accept spaces between digits, you don't accept comma at start/end, but you accept space before and after comma, you accept several consecutive spaces and you accept spaces at start/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 when writing regex to match a list of elements "E" delimited by a separator "S" is that you'll certainly have to write the "E" matcher twice (here it is simply "[0-9]+").
- the principle of the pattern is E(SE)*
- E is "[0-9]+" : simply a sequence of digits
- S is " *, *" (notice the spaces) : a comma with optionnal spaces before and after
at this point we have :
/^[0-9]+( *, *[0-9]+)*$/
we improves it a little, so it also accepts spaces at start/end, spaces-only and empty strings :
/^ *([0-9]+( *, *[0-9]+)*)? *$/
Note I personally prefer to use [0-9] instead of \d, I think it is less confusing to read.
精彩评论