How can I create a regular expression that accepts a certain number at most once

4

I'm learning how to use Regex and would like to know if I can get it to accept a maximum of 2 in some sequence (it may contain letters or numbers)

Eg: "sskfdam09471928" Approved

"asldk02210920139" Disapproved by repeating twice

    
asked by anonymous 03.07.2018 / 23:05

2 answers

9

With regex you can do it like this:

const a = 'sskfdam09471928';
const b = 'asldk02210920139';

function validar(str) {
  return !!str.match(/^[^2]*2?[^2]*$/);
}
console.log(validar(a)); // true
console.log(validar(b)); // false

The idea of regex is:

  • ^[^2]* - no 2 at the beginning of the string, 0 times or more
  • 2 - a 2 in the middle of the string
  • [^2]*$ no 2 at the end of the string, 0 times or more

Alternative ways:

function validar(str) {
  return str.indexOf('2') === str.lastIndexOf('2');
}

function validar(str) {
  return str.split('').filter(char => char === '2').length <= 1;
}
    
03.07.2018 / 23:11
8

Just to give you another alternative, you can also resolve it with a regex using positive lookahead :

2(?=.*2)

Explanation

2   - Procura pelo 2
(?= - Que tenha à frente
.*  - Qualquer coisa
2)  - E outro dois

This regex indicates whether 2 is repeated. If you want to know if it is not repeated, just reverse the result with a not ! .

Example:

console.log(!/2(?=.*2)/g.test("sskfdam09471928"));
console.log(!/2(?=.*2)/g.test("asldk02210920139"));
    
03.07.2018 / 23:39