RegEx expression to validate input string

I am looking for a regular expression to validate input containing at least three of the following four groups of characters:

English uppercase characters (A through Z) English lowercase characters (a through z) Numerals (0 through 9) Non-alphabetic characters (such as !, $, #, %) 

Thanks in advance.

Edit: this is for the .NET Framework

0
source share
2 answers

Not in one regex, but think this is a way:

 int matchedGroupCount = 0; matchedGroupCount += Regex.IsMatch(input, "[az]") ? 1 : 0; matchedGroupCount += Regex.IsMatch(input, "[AZ]") ? 1 : 0; matchedGroupCount += Regex.IsMatch(input, "[0-9]") ? 1 : 0; matchedGroupCount += Regex.IsMatch(input, "[!*#%, etc..]") ? 1 : 0; if (matchedGroupCount >= 3) pass else failed 
+4
source

I can't think of a direct way to do this, to be honest: regular expressions don't really support "must contain". What language do you write this in? Personally, I would do this by checking each regex in turn and counting how many matches you get, so in python it would be something like this:

 #!/usr/bin/python import re count = 0 mystring = "password" regexp = re.compile(r'[AZ]') if regexp.search(mystring) is not None: count += 1 regexp = re.compile(r'[az]') if regexp.search(mystring) is not None: count += 1 # etc if count < 3: print "Not enough character types" 

You can also do this more cleanly:

 #!/usr/bin/python import re regexpArray = [re.compile(r'[AZ]'), re.compile(r'[az]'), re.compile(r'\d'), re.compile(r'[^A-Za-z0-9]')] count = 0 for regexp in regexpArray: if regexp.search(mystring) is not None: count += 1 if count < 3: print "Not enough character types" 

In addition, you may have a very complex regular expression with a large number of options (in different orders) or one of the various password strength checks that you can find using Google.

Edit

The python path for this without regex will look like this. I am sure that the .NET equivalent for this will be much faster than the regular expression.

 #!/usr/bin/python import string mystring = "password" count = 0 for CharacterSet in [string.ascii_lowercase, string.ascii_uppercase, "0123456789", r'''!"Β£$%^&*()_+-=[]{};:'@#~,<.>/?\|''']: # The following line adds 1 to count if there are any instances of # any of the characters in CharacterSet present in mystring count += 1 in [c in mystring for c in CharacterSet] if count < 3: print "Not enough character types" 

There may be a better way to generate a list of characters.

0
source

All Articles