什么是最适合用于以逗号分隔的整数的正则表达式?它也可以在逗号之间包含空格,并且该字段不是必需的,这意味着它可以为空。
123,98549
43446
etc..
123,98549
43446
etc..
这是一个非常基础的内容,可能适合您:
/^[\d\s,]*$/
只要字符串仅包含数字、空格和逗号,它就会匹配。这意味着"123 456"将通过,但我不知道这是否有问题。
/^\s*(\d+(\s*,\s*\d+)*)?\s*$/
"" true
"123" true
"123, 456" true
"123,456 , 789" true
"123 456" false
" " true
" 123 " true
", 123 ," false
解释:
/^\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
(\d+)
逗号和空格不应该是问题,因为您只需要遍历组即可。我不知道你指的这个字段是什么
这个字段不是必需的,也就是说它可以为空
除此之外,我认为这应该可以工作
/^((\b)*[0-9]+(\b)*[,])*(\b)*[0-9]+(\b)$/
这个问题应该更加明确:例如,您是否接受数字之间的空格?您是否接受逗号在开头/结尾?您是否接受逗号前面的空格?您是否接受几个连续的空格?您是否接受开头/结尾的空格?
我会假设最有可能的情况,即您不接受数字之间的空格,不接受逗号在开头/结尾,但您接受逗号前后的空格,接受几个连续的空格,并且接受开头/结尾的空格。
/^ *([0-9]+( *, *[0-9]+)*)? *$/
编写用于匹配由分隔符“S”分隔的元素列表“E”的正则表达式时,关键是您肯定必须两次编写“E”匹配器(这里只是“[0-9]+”)。
此时我们有:
/^[0-9]+( *, *[0-9]+)*$/
/^ *([0-9]+( *, *[0-9]+)*)? *$/
请注意,我个人更喜欢使用 [0-9] 而不是 \d,我认为这样更易于阅读。