Java Regex Username Password examples
User name Regex Pattern
^[a-z0-9_-]{3,15}$Split this pattern
^ | Start of the line |
[a-z0-9_-] | Match characters and symbols in the list, a-z, 0-9 , underscore , hyphen |
{3,15} | Length at least 3 characters and maximum length of 15 |
$ | End of the line |
Password Regular Expression Pattern
((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})( | Start of group |
(?=.*\d) | must contains one digit from 0-9 |
(?=.*[a-z]) | must contains one lowercase characters |
(?=.*[A-Z]) | must contains one uppercase characters |
(?=.*[@#$%]) | must contains one special symbols in the list "@#$%" |
. | match anything with previous condition checking |
{6,20} | length at least 6 characters and maximum of 20 |
) | End of group |
Example
package mycollectiontest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
private Pattern pattern;
private Matcher matcher;
private static final String USERNAME_PATTERN = "^[a-z0-9_-]{3,15}$";
private static final String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
public RegexExample() {
pattern = Pattern.compile(USERNAME_PATTERN);
System.out.println("input : pretech user name " + validate("pretech"));
pattern = Pattern.compile(PASSWORD_PATTERN);
System.out.println("input : password " + validate("pretech@gmail.com"));
}
public boolean validate(final String username) {
matcher = pattern.matcher(username);
return matcher.matches();
}
public static void main(String[] args) {
new RegexExample();
}
}
Output
input : pretech user name true
input : password false
No comments:
Post a Comment