3

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: true

AAAsjs21js1: false

ASaaak12: false

My regex attempt, but only matches exactly 2 uppercase letters:

([a-z]*[A-Z]{1}[a-z]*){2}
timolawl
  • 4,934
  • 9
  • 28

4 Answers4

3

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

timolawl
  • 4,934
  • 9
  • 28
1

The solution using String.match function:

function checkWord(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"));  // true
console.log(checkWord("WindowA1k2j3"));  // true
console.log(checkWord("AAAsjs21js1"));   // false
console.log(checkWord("ASaaak12"));      // false
RomanPerekhrest
  • 73,078
  • 4
  • 37
  • 76
1

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.

Community
  • 1
  • 1
bobble bubble
  • 11,968
  • 2
  • 22
  • 34
0

Without lookahead, pure regex:

http://regexr.com/3ddva

Basically, just checks every case.

Community
  • 1
  • 1
Kenny Lau
  • 421
  • 4
  • 13