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

Asked

Viewed 58 times

4

I am learning to use Regex and I would like to know if I can make it accept at most a number 2 in some sequence (can contain letters or numbers)

Ex. "sskfdam09471928" Approved

"asldk02210920139" Failed to repeat twice

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]* - none 2 at the beginning of the string, 0 times or more
  • 2 - one 2 in the middle of the string
  • [^2]*$ none 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;
}
  • Okay, thanks for helping me, I understand

  • Or something like that that would be true for the reprobates: https://regex101.com/r/KXNrdM/1

  • @bfavaretto and how about an answer? ;) that solution with ! is shorter than mine

  • @bfavaretto this regex with cases of 2 spread by the string no longer gives... only side by side

  • @Do you know other ways to solve this? I want to learn different ways, although this has already helped me

  • @Rodolfo, I think my interpretation was different from Sergio’s. It can not have sequence 2, or there can be no more than one 2 in string?

  • There can be no more than a 2 in the string

  • Then my link above is not worth, worth this answer. Possibly there are other ways with regex. And you can solve that same problem without regex as well. @Rodolfo

  • Thank you, I’ll get them!

Show 4 more comments

8

Just to give one more alternative, also to solve 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 if the 2 repeats. If you want to know if it is not repeated simply invert the result with a not !.

Example:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.