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
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
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 more2
- one 2
in the middle of the string[^2]*$
none 2
at the end of the string, 0 times or moreAlternative ways:
function validar(str) {
return str.indexOf('2') === str.lastIndexOf('2');
}
function validar(str) {
return str.split('').filter(char => char === '2').length <= 1;
}
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 javascript regex
You are not signed in. Login or sign up in order to post.
Okay, thanks for helping me, I understand
– Rodolfo
Or something like that that would be true for the reprobates: https://regex101.com/r/KXNrdM/1
– bfavaretto
@bfavaretto and how about an answer? ;) that solution with
!
is shorter than mine– Sergio
@bfavaretto this regex with cases of
2
spread by the string no longer gives... only side by side– Sergio
@Do you know other ways to solve this? I want to learn different ways, although this has already helped me
– Rodolfo
@Rodolfo, I think my interpretation was different from Sergio’s. It can not have sequence
2
, or there can be no more than one2
in string?– bfavaretto
There can be no more than a 2 in the string
– Rodolfo
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
– bfavaretto
Thank you, I’ll get them!
– Rodolfo