1

I need regex that checks if string has at least 3 uppercase, 3 lowercase letters and at least one specialcharacter.

Currently I have this:

^(?=.*[a-z]{3,})(?=.*[A-Z]{3,})(?=.*\d)(?=.*(_|[^\w])).+$

But it only works if the characters are next to eachother.

Example of what it should match:

S4L4S6na#a
user3482304
  • 151
  • 1
  • 2
  • 12

1 Answers1

3

This will work

(?=(.*[A-Z]){3})(?=(.*[a-z]){3})(?=.*(_|[^\w]))

If you want to also include digit

(?=.*\d)(?=(.*[A-Z]){3})(?=(.*[a-z]){3})(?=.*(_|[^\w]))

Regex Demo

Further optimization as per comments

You can use non-greedy approach, which optimizes the above regex and use [\W_] instead of (_|[^\w])

(?=(.*?[A-Z]){3})(?=(.*?[a-z]){3})(?=.*?[\W_])

Reason for alternation being slower than character class

Community
  • 1
  • 1
rock321987
  • 10,942
  • 1
  • 30
  • 43