Davit Avetisyan - 1 year ago 71

Javascript Question

Hello I need to words that contains exactly 2 uppercase letters and 3 numbers. Numbers and uppercase letters can be at any positions in word.

HelLo1aa2s3d: true

WindowA1k2j3: true

AAAsjs21js1: false

ASaaak12: false

`([a-z]*[A-Z]{1}[a-z]*){2}`

this one I figure out that contains exactly 2 uppercase numbers.

Answer Source

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
```