How i can check group of number like this in JavaScript Regexp?

Viewed 63

How to match group of 10 numbers 1 or mores times (it should separate by , if more than one group).

pattern: 0123456789,9876543210,...

AND each group must start with 00

pattern: 0023456789,0076543210,00...

I try to do like this and stuck:

/(?:\d{10}(?:,(?!$)|$)){1,}/.test('1111111111')

There are patterns i want to:

/pattern/.test('0012345678') // should true
/pattern/.test('0012345678,0012345678') // should true
3 Answers

Here's a regex that will do this.

/^00[0-9]{8}(,00[0-9]{8})*$/

Try this regexp /^(00\d{8})(?:,(00\d{8}))*$/ to match a group of 10 numbers 1 or more times.

const pattern = /^(00\d{8})(?:,(00\d{8}))*$/
console.log(pattern.test('0123456789')) //should false
console.log(pattern.test('0123456789,9876543210')) //should false
console.log(pattern.test('0023456789')) //should true
console.log(pattern.test('0023456789,0076543210')) //should true
console.log(pattern.test('0023456789,0076543210,0123456789')) //should false
console.log(pattern.test('00123456789999999')) //should false
console.log(pattern.test('00123456789999999,0023456789')) //should false
console.log(pattern.test('0023456789,00123456789999999')) //should false

This is not a regex but it works perfectly!

console.log(check('0012345678'));
console.log(check('0012345678,0012345678'));
console.log(check('hi'));
console.log(check('00hello123,0011111111'));
console.log(check());
console.log(check(''));
console.log(check('0000000000'));
/* expected output:

   true
   true
   false
   false
   false
   false
   true
*/

function check(numbers) {
  if (numbers === undefined) {
    return false;
  }
  numbers = String(numbers);
  if (numbers == '') {
    return false;
  }
  for (var i of numbers.split(',')) {
    if (i.length != 10) { // length must be 10
      return false;
    }
    if (i.replace(/[0-9]*/, '') != '') { // contains only numbers
      return false;
    }
    if (!i.startsWith('00')) { // starts with "00"
      return false;
    }
  }
  return true;
}

Related