Search code examples
phpregexregular-language

Regular expression to evaluate password string


I'm working on a little project, I need to evaluate a string of only four characters[I can write little bit REs, but this one got me.]. I need to write a regular expression that will must match 1 upper case word, 1 lower case word, one digit and one random character like [a-zA-Z0-9]. order doesn't matter in the string.

Here are some case strings that it should pass or fail.

Valid words: Abn1, GGh3, 89jK….

Invalid words: abcd, 112a, abDb, 2Ab, 4, AA, ….

any help or heads up appreciated.


Solution

  • Muultiple lookaheads is your answer

    \b(?=[a-zA-Z0-9]*[a-z])(?=[a-zA-Z0-9]*[A-Z])(?=[a-zA-Z0-9]*[0-9])[a-zA-Z0-9]{4}\b
    
    (?=[a-zA-Z0-9]*[a-z])    # string contains any lowercase character
    (?=[a-zA-Z0-9]*[A-Z])    # string contains any uppercase character
    (?=[a-zA-Z0-9]*[0-9])    # string contains any digit
    [a-zA-Z0-9]{4}           # 4 characters, since the 4th is  the type that can fit in any of the three
    

    If the string is from a single input (like a 4-character textbox, you should should replace the word boundaries (\b) with ^ and $, like

    ^(?=[a-zA-Z0-9]*[a-z])(?=[a-zA-Z0-9]*[A-Z])(?=[a-zA-Z0-9]*[0-9])[a-zA-Z0-9]{4}$