Regex to match at least 2 digits, 2 letters in any order in a string

java, regex

Solution

If you don't want letters to have to be consecutive `(?=.*[a-zA-Z].*[a-zA-Z])` is correct approach. Same goes to digits `(?=.*\\d.*\\d)` or `(?=(.*\\d){2})`.

Try this regex

(?=^.{8,30}$)(?=(.*\\d){2})(?=(.*[A-Za-z]){2})(?=.*[!@#$%^&*?])(?!.*[\\s])^.*

Problem

I'm trying to create a regex to pattern match (for passwords) where the string must be between 8 and 30 characters, must have at least 2 digits, at least 2 letters (case-insensitive),at least 1 special character, and no spaces. I've got the spaces and special character matching working, but am getting thrown on the 2 digits and 2 letters because they don't need to be consecutive. i.e. it should match `a1b2c$` or `ab12$` or `1aab2c$`. Something like this for the letters? ``` (?=.*[a-zA-Z].*[a-zA-Z]) // Not sure. ``` This string below works, but only if the 2 letters are consecutive and the 2 numbers are consecutive..it fails if the letters, numbers, special chars are interwoven. ``` (?=^.{8,30}$)((?=.*\\d)(?=.*[A-Za-z]{2})(?=.*[0-9]{2})(?=.*[!@#$%^&*?]{1})(?!.*[\\s]))^.* ```

Original source

Related problems