Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check uppercase AND lowercase

Tags:

regex

I'm searching from a while for the regular expression that matches a word containing between 8 and 20 characters combining uppercases AND lowercases:

Here an example of valid expression : AaAaAaAaA or aaaaaaaaA

Not Valid expression example : aaaaaaaaa or AAAAAAAA

What I did till now is : ^[a-z][A-Z]{8,20}$, but as you can see, that doesn't work

Somebody have an idea for that ?

Best regards

like image 690
Ali Avatar asked Feb 12 '23 18:02

Ali


2 Answers

Credit to anubhava, lookahead was the way to go.

\b(?=[a-z]+[A-Z]+|[A-Z]+[a-z]+)[a-zA-Z]{8,20}\b

The look ahead ensures that there is at least one capital and lowercase letter in any order in the match. This will match whole words that are 8-20 chars long and contain at least 1 upper case and at least 1 lower case letter.

^(?=[a-z]+[A-Z]+|[A-Z]+[a-z]+)[a-zA-Z]{8,20}$

Will anchor to the beginning and end of the string, and thus match only a single word.

You can see it in action here http://regex101.com/r/uE5lT4/4

Edit: First version did not match a word if the only capital was the last letter.

like image 169
Jenn Avatar answered Feb 15 '23 09:02

Jenn


Your character class needs to include both a-z and A-Z ranges. Regex should be:

^[a-zA-Z]{8,20}$

Your regex:

^[a-z][A-Z]{8,20}$

is actually checking for a lower case character followed by 8 to 20 upper case alphabets.

Update: to make sure you match at least one lower and one upper case alphabet use lookahead regex like this:

^(?=[A-Z]*[a-z])(?=[a-z]*[A-Z])[a-zA-Z]{8,20}$

RegEx Demo

like image 34
anubhava Avatar answered Feb 15 '23 10:02

anubhava