2

I want to set a password which do not allow specific special characters like

-_\

and my regular expression is as follows

PatternCompiler compiler = new Perl5Compiler();
PatternMatcher matcher = new Perl5Matcher();
pattern = compiler.compile("^(?=.*?[a-zA-Z])(?=.*?[0-9])([A-Za-z0-9-/-~][^\\\\\\\\_\-]*)$");

It is working partially. If i place unwanted special characters between the string and start of the string still it is matching the password

P@ssword123    --correct
-password@123  --it should not match
-passowrd"11   --it should not match
\password123   --it should not match
_@111Password  --it should not match
p@sswor"123    --correct

Any where in the string if i find -_\ regular expression should not match. Using Apache api for matching pattern in java

Kiran
  • 199
  • 4
  • 5
  • 14
  • better to whitelist rather than blacklist see http://stackoverflow.com/questions/756567/regular-expression-for-excluding-special-characters – Scary Wombat Mar 23 '17 at 05:31
  • Except those three remaining all characters are needed in the keyborad so that is the reason i choose blacklist – Kiran Mar 23 '17 at 05:42

1 Answers1

3

Here is a general regex you can try:

^((?=[A-Za-z])(?![_\-]).)*$
    ^^ whitelist  ^^ blacklist

You can include both a positive and negative lookahead assertion which will check for the presence or absence of a character class. Something like the following might work for you:

String password = "-passw@rd";
// nice trick: by placing hyphen at the end of the character class,
// we don't need to escape it
String pattern = "^((?=[A-Za-z0-9@])(?![_\\\\-]).)*$";
if (password.matches(pattern)) {
    System.out.println("valid");
}
else {
    System.out.println("not valid");
}

That being said, I would strongly recommend that you search around for regular expressions for passwords. This is a known and old problem, and a lot of good work has already been done in this area, including on Stack Overflow.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360