What would be the regex pattern for a set of numbers separated with a comma
The possible values are...
1 (it 开发者_如何学Gowill always start with a number)
1,2
4,6,10
You can try something like this:
^[0-9]+(,[0-9]+)*
This should do it:
(\d+,?)+
This will do:
-?[0-9]+(,-?[0-9]+)*
Or, if you want to be pedantic and disallow numbers starting with 0 (other than 0 itself):
(0|-?[1-9][0-9]*)(,(0|-?[1-9][0-9]*))+
Floating-point numbers are left as an exercise to the reader.
You'll want
(?<=(?:,|^))\d+(?=(?:$|,))
Regex Buddy explains it as...
Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=(?:,|^))»
Match the regular expression below «(?:,|^)»
Match either the regular expression below (attempting the next alternative only if this one fails) «,»
Match the character "," literally «,»
Or match regular expression number 2 below (the entire group fails if this one fails to match) «^»
Assert position at the start of the string «^»
Match a single digit 0..9 «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=(?:$|,))»
Match the regular expression below «(?:$|,)»
Match either the regular expression below (attempting the next alternative only if this one fails) «$»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»
Or match regular expression number 2 below (the entire group fails if this one fails to match) «,»
Match the character "," literally «,»
I would explain it as, "match any string of digits confirming that before it comes either the start of the string or a comma and that after it comes either the end of the string or a comma". nothing else.
The important thing is to use non-capturing groups (?:) instead of simply () to help overall performance.
精彩评论