Reputation: 2457
I'm trying to combine these regular expressions into one. Anybody know if this is possible?
Basically I'm trying to check if a string has a lowercase letter, an uppercase letter and a number.
(.*[a-z]+.*)
(.*[A-Z]+.*)
(.*[0-9]+.*)
So these strings that would all pass
aA1
a1A
Aa1
A1a
1aA
1Aa
Examples that would return false
aa1
AA1
a1a
AAa
a1
1a
1AA
1A
etc..
Upvotes: 2
Views: 91
Reputation: 164769
Yes, but it's nasty. (Examples are in Perl)
my $re = qr{(?:
([a-z]+) |
([A-Z]+) |
([0-9]+)
)+}x;
All of $1
, $2
, and $3
must be defined (true won't cut it because 0 is false).
$string =~ $re;
print "Match" if defined $1 && defined $2 && defined $3;
You're better off for everyone's sake keeping it at three simple regexes and writing a subroutine.
sub is_valid_string {
my $str = shift;
return 0 unless $str =~ /[a-z]/;
return 0 unless $str =~ /[A-Z]/;
return 0 unless $str =~ /[0-9]/;
return 1;
}
Upvotes: 1
Reputation: 726539
A very simple approach is to enumerate all six combinations:
[a-z][A-Z][0-9]|[a-z][0-9][A-Z]|[A-Z][a-z][0-9]|[A-Z][0-9][a-z]|[0-9][a-z][A-Z]|[0-9][A-Z][a-z]
Essentially, you've got characters of three types - Upper, Lower, and Digit. The six combinations are
LUD|LDU|ULD|UDL|DLU|DUL
As you can see, this gets complex pretty quickly. If you are dong it for password checking, doing character class counting in the host language is a better choice.
Upvotes: 1