Reputation: 4445
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.
Upvotes: 1
Views: 108
Reputation: 5510
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}$
Upvotes: 3
Reputation: 3329
Single RegExp is not a good way to do that.
The best solution to just check your rules in the loop iterating characters.
As an option you can write 3 simple Regexps for each rule, instead of one big Regexp.
Upvotes: -1