0

I have created regex for password validation in a Java app. The regex I created is below for below requirement.

^[\\p{Alnum}#.!@$*&_]{5,12}$
  1. At least 5 chars and max 12 chars
  2. Contains at least one digit
  3. Contains at least one char
  4. may contain chars within a set of special chars (#.!@$*&_)
  5. Does not contain space, tab, etc.

I am missing 1 and 2 like if I give "gjsajhgjhagfj" or "29837846876", it should fail. But it's not happening.

Could anyone help please?

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
Jacob
  • 420
  • 5
  • 15
  • Is there a reason you restrict it to 12 chars maximum? This doesn't seem logical to me. – Sebastian Proske Mar 08 '16 at 23:29
  • There is a reason which I can't share online – Jacob Mar 08 '16 at 23:33
  • No worries, the good thing is that there are always people willing to help, do NOT be discouraged... Everyone deserved to be helped as long as he shows that he already did some effort and he failed to achieve what he wants, which you clearly did <3 – Enissay Mar 08 '16 at 23:56
  • See [Reference - Password Validation](https://stackoverflow.com/questions/48345922/reference-password-validation/48346033#48346033) – ctwheels Jan 14 '21 at 15:06

1 Answers1

3

You can use lookaheads to force conditions 1 & 2:

^(?i)(?=.*[a-z])(?=.*[0-9])[a-z0-9#.!@$*&_]{5,12}$

DEMO

(?i) is for insensitive match, the same as Pattern.CASE_INSENSITIVE flag for your compile function:

Pattern.compile(regex, Pattern.CASE_INSENSITIVE)

You can read more about Lookaheads HERE

Enissay
  • 4,969
  • 3
  • 29
  • 56