NoBullMan
NoBullMan

Reputation: 2184

Regex - validating comma-separated list of numbers, 1 to 3 digits long

I am trying to validate a comma-separated list of numbers where a number can be 1 to 3 digits, can start with 0 but cannot be 0 (0, 00 or 000). I am using below but when I test '44,222,555' I get invalid:

^([1-9]|[0-9][1-9]|[0-9][0-9][1-9](?:,(?:[1-9]|[0-9][1-9]|[0-9][0-9][1-9]))*)$

I think 90 would be invalid too here but should be valid

Upvotes: 1

Views: 152

Answers (2)

SoEzPz
SoEzPz

Reputation: 15912

In the case where

NOTE: Depending on the size of the string, a speed increase will be gained by not using the global flag.

  • One to three numbers allowed per set
  • one to many sets allowed
  • 0, 00, 000 zero based combinations are not allowed
  • 01, 010, 001, 100 zero based combinations are allowed
  • If more than one set of numbers, then one comma of separation between sets
  • Not allowed to end with a comma

let regex = new RegExp('^((?!0+\\b)[0-9]{1,3}\,?\\b)+$');

// NOTE: If using literal notation /regex/.test() then "\" is not escaped.
// i.e. '^((?!0+\\b)[0-9]{1,3}\,?\\b)+$' becomes /^((?!0+\b)[0-9]{1,3}\,?\b)+$/
// /^((?!0+\b)[0-9]{1,3}\,?\b)+$/.test(string);

console.log('Passes question test: 44,222,555 ', regex.test('44,222,555'));
console.log('Passes question test: 90 ', regex.test('90'));
console.log('Can contain multiple sets of one to three numbers: ', regex.test('1,22,333'));
console.log('Cannot have more than three numbers in a set 1234', !regex.test('1234'));
console.log('Can have one number in a set ', regex.test('1'));

console.log('Cannot have 0 alone as a set: ', !regex.test('0'));
console.log('Cannot have 00 alone as a set: ', !regex.test('00'));
console.log('Cannot have 000 alone as a set: ', !regex.test('000'));

console.log('Cannot end in a comma ', !regex.test('123,'));

console.log('Cannot contain multiple commas next to each other ', !regex.test('123,,694'));
console.log('Allowed zero combinations are 00#, #00, 0#0, 00#, ##0, 0## ', regex.test('001,100,010,001,110,011'));
console.log('Cannot be just a comma ', !regex.test(','));
console.log('Cannot be a blank string ', !regex.test(''));

Upvotes: 0

anubhava
anubhava

Reputation: 784898

You may use a negative lookahead to simplify your regex:

/^(?!0+\b)[0-9]{1,3}(?:,(?!0+\b)[0-9]{1,3})*$/gm

RegEx Demo

(?!0+\b) is negative lookahead that will fail the match if we have one or more zeroes before word boundary ahead of current position.

Upvotes: 1

Related Questions