Regular expression for password

How to validate passwords using regular expressions! It took me a whole day to understand that For reference of similar people. .. ..

Required specifications

^(?=.*[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);
	}
}

reference

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

Miscellaneous notes

Premise

Language: Java8

Main subject

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

Regular expression for password
[Ruby] Regular expression for secure password policy setting
Regular expression basics
JS regular expression
Ruby regular expression
^, $ in Rails regular expression
java regular expression summary
/ Mask delimited user ID / password password with regular expression
[Ruby/Rails] How to generate a password in a regular expression
Full-width / half-width judgment regular expression
A little regular expression story Part 1
A little regular expression story Part 2
Apply regular expression matching with JSON Sassert
Ruby: Regular expression summary * Code sample available