Skip to content Skip to sidebar Skip to footer

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" - multiline

Regex101

Solution 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"));      // false

Solution 3:

I think, you need just one lookahead.

^(?=(?:\D*\d){3}\D*$)(?:[^A-Z]*[A-Z]){2}[^A-Z]*$
  • \d is a short for digit. \D is the negation of \d and 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.

Demo at regex101

If you want to allow only alphanumeric characters, replace [^A-Z] with [a-z\d]like in this demo.

Solution 4:

Without lookahead, pure regex:

http://regexr.com/3ddva

Basically, just checks every case.

Post a Comment for "Regular Expression With Exactly 2 Uppercase Letters And 3 Numbers"