Ishmeet Singh
Ishmeet Singh

Reputation: 139

Validate comma separated string of numbers with Regular Expression?

I need a regular expression for validation of 3 numbers then , and again 3 numbers and again basically any number of times. And comma can be at the begining or it can be at the end (but strictly one).

So, these are valid inputs:

,111,111,

112,112,

,112,112,113,114,111,

,114,115

,142,

,141

Invalid inputs:

,,

, ,

,,145,,,

I have made like:

var re = /^[0-9]{3}([,][0-9]{3})*$/;

But it is not working well and it is only accepting 2 groups. And always want comma at the end.

Upvotes: 2

Views: 1030

Answers (1)

anubhava
anubhava

Reputation: 784898

You may use this regex:

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

RegEx Demo

Replace \d with [0-9] if it is not supported in your regex platform.

RegRx Description:

  • ^,?: Match an optional , at the start
  • (?:\d{3},)*: Match a non-capturing group 0 or more times. We match a 3 digit number followed by , inside this group.
  • \d{3}: Match a 3 digit number
  • ,?$: Match an optional , at the end

Upvotes: 1

Related Questions