Reputation: 489
I need your help to write a regex for validating a string that should follow below rule.
"2 Alphabet and 4 Numeric. And it can be a mixed string"
Eg: 11a1a1 or 1a11a1..etc
Thanks for your help.
Upvotes: 1
Views: 72
Reputation: 18950
Try it like this:
^(?=.*\d.*?\d.*?\d.*?\d)(?=.*[a-zA-Z].*?[a-zA-Z]).+$
Since the question does not specify how long such a string could be, any length is accepted as long as the basic rule is fulfilled.
const regex = /^(?=.*\d.*?\d.*?\d.*?\d)(?=.*[a-zA-Z].*?[a-zA-Z]).+$/gm;
const str = `aa1111
b1b111
1111aa
11a1a1
1a11a1
aaaa11
bbb111
b1b1b1
b11b1b`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match) => {
console.log(`Found match: ${match}`);
});
}
Upvotes: 1