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?

4
  • Is there a reason you restrict it to 12 chars maximum? This doesn't seem logical to me. Commented Mar 8, 2016 at 23:29
  • There is a reason which I can't share online Commented Mar 8, 2016 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 Commented Mar 8, 2016 at 23:56
  • See Reference - Password Validation Commented Jan 14, 2021 at 15:06

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.