用逗号分隔的整数的最佳正则表达式是什么?它还可以包含逗号之间的空格,并且不需要该字段,这意味着它可以是空白的.
123,98549
43446
Run Code Online (Sandbox Code Playgroud)
等等..
这是一个非常基本的,可能适合你:
/^[\d\s,]*$/
Run Code Online (Sandbox Code Playgroud)
只要它只包含数字,空格和逗号,它就会匹配任何字符串.这意味着"123 456"将通过,但我不知道这是否是一个问题.
/^\s*(\d+(\s*,\s*\d+)*)?\s*$/
Run Code Online (Sandbox Code Playgroud)
这个有这些结果:
"" true
"123" true
"123, 456" true
"123,456 , 789" true
"123 456" false
" " true
" 123 " true
", 123 ," false
Run Code Online (Sandbox Code Playgroud)
说明:
/^\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
Run Code Online (Sandbox Code Playgroud)