tags:

views:

206

answers:

3

I'm looking for some help creating a regex that requires 8 char (at a minimum) along w/ 1 number and 1 char (not special char).

example: a1234567 is valid but 12345678 is not

Any help for a regex newb?

EDIT:

Thanks for the quick replies- the implementation that worked in VB is shown below

Dim ValidPassword As Boolean = Regex.IsMatch(Password, "^(?=.*[0-9])(?=.*[a-zA-Z])\w{8,}$")
+2  A: 

You really need an expression with three regexes :)

 /\w{8}/

gives minimum 8 A-Z, a-z, 0-9 and _ chars

/\d/

finds a single digit

/[A-Za-z]/

finds a single letter.

So, in Perl:

$string =~ /\w{8}/ and $string =~ /\d/ and $string =~ /[A-Za-z]/
Jeremy Smyth
+4  A: 

something like

^(?=.*[0-9])(?=.*[a-zA-Z])\w{8,}$

would work

dissected:

  • ^ the beginning of the string
  • (?=.*[0-9]) look ahead and make sure that there is at least 1 digit
  • (?=.*[a-zA-Z]) look ahead and make sure there is at least 1 letter
  • \w{8,} actually match the 8+ characters
  • $ the end of the string

Edit: if you want extra characters (that don't count for the 1 letter requirement) use

^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$

this will allow for any character besides newline to be used

If you only want certain characters allowed, replace \w in the first regex with [A-Za-z0-9@#$%^&*] with your choice of symbols

^(?![0-9]$)(?![a-zA-Z]*$)\w{8,}$

cobbal
Not bad... you'd need to check for underscores, though, wouldn't you?
Michael Myers
yep, fixed now.
cobbal
currently this requires a lower case - what if i wanted an OR like statement - so 1 lower case char OR 1 upper case char ? All else is 100%
Toran Billups
I'm not exactly sure what you're asking for "A1234567" "a1234567" and "Aa123456" all are matched by this. could you give an example of something that you want to match, but doesn't currently?
cobbal
Ahh you are correct (sorry) - I realized what it won't allow is any special char like $ or % - is it possible to allow this?
Toran Billups
+1  A: 

Try this regular expression with positive look-ahead assertion:

(?=[a-zA-Z]*[0-9])(?=[0-9]*[a-zA-Z])^[0-9a-zA-Z]{8,}$

The parts are:

  • (?=[a-zA-Z]*[0-9]) checks for at least one character of 0-9
  • (?=[0-9]*[a-zA-Z]) checks for at least one character of the set a-z, A-Z
  • ^[0-9a-zA-Z]{8,}$ checks for the length of at least 8 occurrences of 0-9, a-z, A-Z.

Or with just the basic syntax:

^([0-9][a-zA-Z][0-9a-zA-Z]{6,}|[0-9]{2}[a-zA-Z][0-9a-zA-Z]{5,}|[0-9]{3}[a-zA-Z][0-9a-zA-Z]{4,}|[0-9]{4}[a-zA-Z][0-9a-zA-Z]{3,}|[0-9]{5}[a-zA-Z][0-9a-zA-Z]{2,}|[0-9]{6}[a-zA-Z][0-9a-zA-Z]+|[0-9]{7}[a-zA-Z][0-9a-zA-Z]*|[a-zA-Z][0-9][0-9a-zA-Z]{6,}|[a-zA-Z]{2}[0-9][0-9a-zA-Z]{5,}|[a-zA-Z]{3}[0-9][0-9a-zA-Z]{4,}|[a-zA-Z]{4}[0-9][0-9a-zA-Z]{3,}|[a-zA-Z]{5}[0-9][0-9a-zA-Z]{2,}|[a-zA-Z]{6}[0-9][0-9a-zA-Z]+|[a-zA-Z]{7}[0-9][0-9a-zA-Z]*)$
Gumbo