Regular Expressions

  • Thread starter Thread starter Roz Lee
  • Start date Start date
R

Roz Lee

I am trying to work out a regular expression which will validate a
password box.

The following rules apply
Must be 8 characters
Must have at least one digit (0-9) and at least one character (a-z or
A-Z)
No special characters allowed except for full stop.

I am struggling to get to grips with regular expressions. Can anyone
help me with this please.
Thanks in anticipation

Ros Lee
 
Maybe we need to && the conditional statements with three regex patterns:
r1 = [a-zA-Z0-9]{8}
r2 = [a-zA-Z]{1,7}
r3 = [0-9]{1,7}

or just use r2 "anded" to r3 with a string length of 8.

Eg.:
option 1: (I like this one better. It has a more definitive and tighter
constraint on the string pattern compared to opt2)
if ((Regex.IsMatch(sPassword, r1)) &&
(Regex.IsMatch(sPassword, r2)) &&
(Regex.IsMatch(sPassword, r3)))

option 2:
if ((Regex.IsMatch(sPassword, r2)) &&
(Regex.IsMatch(sPassword, r3)) &&
(sPassword.Length == 8))


http://www.regular-expressions.info/ has a good tutorial on regex.

Try it see if either works and good luck,
/Js.
 
Just out of curiousity - why use regular expressions? Your problem is
just a few lines of non-regular expression code - why not just code
it the boring old way?
 
Hi Jimi,
Just out of curiousity - why use regular expressions? Your problem is
just a few lines of non-regular expression code - why not just code
it the boring old way?

I am almost writting that forever however in this case, I think it will
needs more lines.
What did you think of?

Cor
 
Jimi said:
...
Suppose the regular expression approach takes 4 lines and 1 hour.

I didn't spend more than 5 minutes on that regex (including testing).
Maybe your regex skills need some training ;-)
My approach to this trivial problem takes 12 lines and 5 minutes.

Including testing? (buffer-overruns, chinese unicode characters...)
(The .net regex-engine already is well-tested)
This is an easy business decision - there is no need to minimize the
number of lines of code if the tradeoff is this drastic.

You don't know the OP's code.
Maybe the password-check-rules should be stored in a configuration file?
Or maybe an admin should be able to modify them?
Maybe the OP uses a validation framework that will only accept regular
expressions?
Or maybe she simple wants to get a better understanding of regular
expressions.
I can see using regular expressions for complex problems, but it's
massive overkill for small problems.

Definitely, but it's hard to tell if this is one of the complex problems or
only a simple one. (see above)

Niki
 
Back
Top