-1

For instance I want to match string only if it has characters "1" and "2" in the same quantity in it.

Input 1: 1932213 (match, since there are same quantity of "1" and "2")
Input 2: 11932213 (don't match, since there are more "1" than "2")

How do I get such a regexp ?
illustration of this could be:
( ?=(.*1){n} ) ( ?=(.*2){n} )

The question is how to put n in regex ?
Thank you!

Rafayel
  • 1
  • 1

1 Answers1

0

This isn't possible with a regex alone, but it's trivial to accomplish programatically:

const getOccurrences = (str, num) => [...str].reduce((a, b) => a + (b === num), 0);
const validate = str => getOccurrences(str, '1') === getOccurrences(str, '2');

console.log(
  validate('1932213'),
  validate('11932213'),
  validate('1'),
  validate('12'),
);

Another approach:

const getOccurrences = (str, num) => (str.match(new RegExp(num, 'g')) || []).length;
const validate = str => getOccurrences(str, '1') === getOccurrences(str, '2');

console.log(
  validate('1932213'),
  validate('11932213'),
  validate('1'),
  validate('12'),
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320