3

I want to write a regex which will match any word consisting of 8 characters and these characters should belong to the charset: [A-Za-z0-9].

However, they should consist of at least one character from each of the 3 charsets (uppercase, lowercase and digits).

This is the regex I am using:

^[a-zA-Z0-9]{8}$

however, this will match examples like:

09823983
language
mainMenu

but I want to match words like:

uXk3mHy9

how can I do this using a regex?

Neon Flash
  • 3,113
  • 12
  • 58
  • 96

2 Answers2

5

You can use three look-aheads in front of your regex:

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]{8}$
kev
  • 155,172
  • 47
  • 273
  • 272
1

Don't do it all in one regex. Regexes are not a magic toolbox from which all solutions must come.

Check for three different conditions rather than cramming them all into one regex. In Perl this would be:

$ok = ( $s =~ /^[a-zA-Z0-9]{8}$/ && $s =~ /[a-z]/ && $s =~ /[A-Z]/ && $s =~ /[0-9]/ );

It is far clearer what your intent is.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152