Make sure you use Matcher.matches()
method, which assert that the whole string matches the pattern.
Your current regex:
"((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])|(?=.*[\\d~!@#$%^&*\\(\\)_+\\{\\}\\[\\]\\?<>|_]).{6,50})"
means:
- The string must contain at least a digit
(?=.*\\d)
, a lower case English alphabet (?=.*[a-z])
, and an upper case character (?=.*[A-Z])
- OR
|
The string must contain at least 1 character which may be digit or special character (?=.*[\\d~!@#$%^&*\\(\\)_+\\{\\}\\[\\]\\?<>|_])
- Either conditions above holds true, and the string must be between 6 to 50 characters long, and does not contain any line separator.
The correct regex is:
"(?=.*[a-zA-Z])(?=.*[\\d~!@#$%^&*()_+{}\\[\\]?<>|]).{6,50}"
This will check:
- The string must contain an English alphabet character (either upper case or lower case)
(?=.*[a-zA-Z])
, and a character which can be either a digit or a special character (?=.*[\\d~!@#$%^&*()_+{}\\[\\]?<>|])
- The string must be between 6 and 50 characters, and does not contain any line separator.
Note that I removed escaping for most characters, except for []
, since {}?()
loses their special meaning inside character class.