Regular expression - Validate username in java
Regular expression of a user name:This regular expression checks whether a user name consists of lowercase only, of digit and symbol '_'. It is the most used filter in several websites.
^[a-z0-9_-]{4,15}$
Explanation:
^: Start
[a-z0-9_-]: allowed characters
{4,15}: the length must be between 4 and 15 characters at most
import java.util.regex.Matcher;Examples:
import java.util.regex.Pattern;
public class regex_username{
private Pattern pattern;
private Matcher matcher;
private static final String USERNAME_PATTERN = "^[a-z0-9_-]{4,15}$";
public regex_username(){
pattern = Pattern.compile(USERNAME_PATTERN);
}
/**
* Validate the username with a regular expression
* @retourne true if the name is valid, otherwise false
*/
public boolean validate(final String username){
matcher = pattern.matcher(username);
return matcher.matches();
}
}
user_99 -> yes
User_99 -> non
aby -> non
superuser#99 -> non
snapper_84 -> yes
965dean -> yes