简体   繁体   中英

Java Regex to not allow String Special Characters

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM