Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

AAAsjs21js1: false

ASaaak12: false

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

([a-z]*[A-Z]{1}[a-z]*){2}
like image 251
Davit Avetisyan Avatar asked Dec 04 '25 13:12

Davit Avetisyan


1 Answers

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

like image 79
timolawl Avatar answered Dec 07 '25 04:12

timolawl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!