How to validate passwords using regular expressions! It took me a whole day to understand that For reference of similar people. .. ..
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!-/:-@[-`{-~])[!-~]{8,48}$
Java sample code
RegexPassword.java
package sample;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexPassword {
public static void main(String[] args) {
Pattern p = Pattern.compile("^$|^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!-/:-@\\[-`{-~])[!-~]*");
Matcher m = p.matcher("aA1!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~");
Boolean result = m.matches();
System.out.println("result:" + result);
}
}
If you know the basic premise of regular expressions If you know the basic premise of regular expressions 2
Easy to read ahead and look back
ASCII character code table is easy to see
For those who do not understand the need for . *
Of (? =. * [A-z])
To use regular expressions in Java
Language: Java8
About regular expressions for passwords First to understand positive look-ahead I wrote and executed the following code to check the operation I was worried about false when it should return true.
package sample;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexWord {
public static void main(String[] args) {
Pattern p = Pattern.compile("^(?=.*[a-z])");
Matcher m = p.matcher("abc");
Boolean result = m.matches();
System.out.println("result:" + result);
}
}
In conclusion, I had to rewrite the line Pattern p = ~
as follows:
Pattern p = Pattern.compile("^(?=.*[a-z]).*");
Recommended Posts