Sam
Sam

Reputation: 8693

What would be the regex pattern for a set of numbers separated with a comma

The possible values are...

1 (it will always start with a number)
1,2
4,6,10

Upvotes: 1

Views: 4050

Answers (4)

Laramie
Laramie

Reputation: 5587

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.

Upvotes: 0

Aragorn
Aragorn

Reputation: 839

You can try something like this:

^[0-9]+(,[0-9]+)*

Upvotes: 4

Adam Rosenfield
Adam Rosenfield

Reputation: 400284

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.

Upvotes: 1

jsnfwlr
jsnfwlr

Reputation: 3798

This should do it:

(\d+,?)+

Upvotes: 2

Related Questions