简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM