I have a regex pattern to confirm that at least one special character is used in passwords.

The problem is it seems like it is validating numbers as well.

In list below the third value though should return false, but returns true.

String[] pass = new String[]{'abcd','@bcd','ab6D','Ab+d','[bc]','a()d'};

(When I change it to any letter (non special char) it properly returns false)

Code below (testing in dev console), with regex:

String REGEX = '((?=.*[`~!@#$%^&*()_+-={}|\\[\\]:\\";\\\'<>?,./]).{4,8})';
String[] pass = new String[]{'abcd','@bcd','ab6D','Ab+d','[bc]','a()d'};

Boolean match;
for (String p : pass) {
    match = Pattern.matches(REGEX, p);

You forgot to escape -, which means that part of the code matches [+-=], which happens to include the following characters: +,-./0123456789:;<=. Instead, make sure you escape the -:

String REGEX = '((?=.*[`~!@#$%^&*()_+\\-={}|\\[\\]:\\";\\\'<>?,./]).{4,8})';

As a side note, you should be able to match easier using a character class:

String regex = '\\p{Punct}.{4,8}';

Which matches any of: !"#$%&'()*+,-./:;<=>?@[\]^_``{|}~

  • Thanks. Just realized that myself. Moved it to the first character. (Is it better to escape?) – Y12K Sep 26 '17 at 1:13
  • @Y12K Use \p{Punct} preferably. It's an alias for basically everything you wanted. – sfdcfox Sep 26 '17 at 1:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.