0

I cannot get a regexp that checks if password has at least one digit to work. This has been answered everywhere but all the answers stop working if split up. For example in this Working Password Validation if I remove:

(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])

from

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\S+$).{8,}$

in order to check for the presence of a single digit, the whole thing stops working

I'm new with regular expressions, this seems to make sense but it doesn't, show me the light if you can.

Community
  • 1
  • 1
David Aleksanyan
  • 2,953
  • 4
  • 29
  • 39
  • What are you trying to do? Check if a password has atleast 1 digit? – Srb1313711 Jul 25 '13 at 11:38
  • I was trying to split up the error messages, so I'd have instead of one big message multiple more specific ones, i.e. must have one digit, then another that says must have a lower case letter and so on... – David Aleksanyan Jul 25 '13 at 12:34

1 Answers1

0

I'm not really sure what you mean by the whole things stops working.

(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])

All the above does is mandate that:

  1. A lower case letter must appear at least once
  2. An upper-case letter must appear at least once
  3. Any of @#$%^&+= must appear at least once

So, there is no reason that taking them out should break anything--they are essentially independent components.

There are myriad ways to check if a String contains a number. How you want to check really depends on your specific requirements. The method used in the presented regex does this through a positive-look ahead: ^(?=.*[0-9])

^ : begins with
.* : matches 0 or more non-newline characters
[0-9]: is a character class that matches the numbers [0,1,2,...,9]
?= is the positive look ahead, which in this case says to match iff there exists at least one number

Hope that helped. You can start off with Oracle's Tutorial on Regular Expressions. After you digest that, I'm sure you'll be able to find more advanced resources via Google.

Steve P.
  • 14,489
  • 8
  • 42
  • 72
  • I'm stumped with this as well. I'm using hibernate 4 to validate. In my bean I have @Pattern(regexp = "^(?=.*[0-9])(?=\\S+$).{8,}$", message = "{must.contain.one.digit}"), and even though I enter a string say "asd43" it errors saying that string must contain a digit – David Aleksanyan Jul 25 '13 at 12:30
  • Ahh, finally I got it, turns out the string size limitation was causing havoc requiring 8 digits. Thank you for the suggestions I definitely need to spend some quality time with that oracle tutorial – David Aleksanyan Jul 25 '13 at 12:42