Regular Expression With Exactly 2 Uppercase Letters And 3 Numbers
I need to match words that contains exactly 2 uppercase letters and 3 numbers. Numbers and uppercase letters can be at any positions in the word. HelLo1aa2s3d: true WindowA1k2j3:
Solution 1:
You can use regex lookaheads:
/^(?=(?:.*[A-Z].*){2})(?!(?:.*[A-Z].*){3,})(?=(?:.*\d.*){3})(?!(?:.*\d.*){4,}).*$/gm
Explanation:
^ // assert position at beginning of line
(?=(?:.*[A-Z].*){2}) // positive lookahead to match exactly 2 uppercase letters
(?!(?:.*[A-Z].*){3,}) // negative lookahead to not match if 3 or more uppercase letters
(?=(?:.*\d.*){3}) // positive lookahead to match exactly 3 digits
(?!(?:.*\d.*){4,}) // negative lookahead to not match if 4 or more digits
.* // select all of non-newline characters if match
$ // end of line
/gm // flags: "g" - global; "m" - multilineSolution 2:
The solution using String.match function:
functioncheckWord(word) {
var numbers = word.match(/\d/g), letters = word.match(/[A-Z]/g);
return (numbers.length === 3 && letters.length === 2) || false;
}
console.log(checkWord("HelLo1aa2s3d")); // trueconsole.log(checkWord("WindowA1k2j3")); // trueconsole.log(checkWord("AAAsjs21js1")); // falseconsole.log(checkWord("ASaaak12")); // falseSolution 3:
I think, you need just one lookahead.
^(?=(?:\D*\d){3}\D*$)(?:[^A-Z]*[A-Z]){2}[^A-Z]*$
\dis a short for digit.\Dis the negation of\dand matches a non-digit(?=opens a positive lookahead.(?:opens a non capturing group.- At
^start(?=(?:\D*\d){3}\D*$)looks ahead for exactly three digits until$the end. - If the condition succeeds
(?:[^A-Z]*[A-Z]){2}[^A-Z]*matches a string with exactly two upper alphas until$end.[^opens a negated character class.
If you want to allow only alphanumeric characters, replace [^A-Z] with [a-z\d]like in this demo.
Post a Comment for "Regular Expression With Exactly 2 Uppercase Letters And 3 Numbers"