vector
vector

Reputation: 7576

regex sets of 5 digits followed by a comma (trailing comma optional)

I've got the following regex:

(\d{5}[,])

This matches the following:

12005,11111,11111,

but how do I make the trailing comma optional?

EDIT:

Acceptable results would be:

12005,

11111,11111,

12005

11111,11111

Unacceptable:

123456

123456,

12345,123456

123456,123456

Upvotes: 1

Views: 920

Answers (5)

Code Jockey
Code Jockey

Reputation: 6721

to make sure you don't match 5 digits from numbers with 6 or more digits, use a word boundary assertion (\b) and beginning of line assertion (^), like so:

(?:\b|^)(\d{5})(?:,|$)

Upvotes: 1

Mike Samuel
Mike Samuel

Reputation: 120586

(\d{5})(?:,|$)

should do the trick.

To break this down,

  • \d{5} - 5 digits
  • (?:...) - just using parentheses to surround the |
  • , - a literal comma
  • $ - end of input
  • ,|$ - a comma or end of input.

The |$ part is needed to avoid spuriously matching groups of digits not separated by commas like "01234567889".


To see it in action, try

 JSON.stringify(
     ["01234", "01234,", "01234,56789", "01234,56789", "", "0123456789"]
     .filter(
         function (s) {
             return /^(?:(\d{5})(?:,|$))+$/.test(s);
         }))

which uses a larger RegExp to match one or more of these groups, so emits

["01234","01234,","01234,56789","01234,56789"]

Upvotes: 5

Lucas
Lucas

Reputation: 14979

Perhaps this:

((?:\d{5},)*\d{5})

Will work if one set of 5 numbers or more than one separated by commas. Or you could get fully explicit and slap the start and end on it:

^((?:\d{5},)*\d{5})$

Upvotes: 1

Eugene Naydenov
Eugene Naydenov

Reputation: 7295

\d{5}[,]* - 0 or more or \d{5}[,]? - 0 or 1.

Upvotes: 0

Shmiddty
Shmiddty

Reputation: 13967

(\d{5}[,]?)

Will match

12005,11111,11111,

or

12005,11111,11111

Upvotes: 2

Related Questions