8

I am trying to get one regular expression that does the following:

  1. makes sure there are no white-space characters
  2. minimum length of 8
  3. makes sure there is at least:
    • one non-alpha character
    • one upper case character
    • one lower case character

I found this regular expression:

((?=.*[^a-zA-Z])(?=.*[a-z])(?=.*[A-Z])(?!\s).{8,})

which takes care of points 2 and 3 above, but how do I add the first requirement to the above regex expression?

I know I can do two expressions the one above and then

\s

but I'd like to have it all in one, I tried doing something like ?!\s but I couldn't get it to work. Any ideas?

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Jose
  • 10,891
  • 19
  • 67
  • 89
  • What is the target language? I've seen this question before (cannot find it) and the solution was to split up the validation in to several steps (so not use only one regex). – Felix Kling Feb 21 '11 at 17:04

2 Answers2

17
^(?=.*[^a-zA-Z])(?=.*[a-z])(?=.*[A-Z])\S{8,}$

should do. Be aware, though, that you're only validating ASCII letters. Is Ä not a letter for your requirements?

\S means "any character except whitespace", so by using this instead of the dot, and by anchoring the regex at the start and end of the string, we make sure that the string doesn't contain any whitespace.

I also removed the unnecessary parentheses around the entire expression.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
7

Tim's answer works well, and is a good reminder that there are many ways to solve the same problem with regexes, but you were on the right track to finding a solution yourself. If you had changed (?!\s) to (?!.*\s) and added the ^ and $ anchors to the end, it would work.

^((?=.*[^a-zA-Z])(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{8,})$
EvilAmarant7x
  • 2,059
  • 4
  • 24
  • 33