1. Overview

This article is about for Java Regular Expression for username. While working with the application development username regular expression is very common, so it’s inspired us to provide common regular expression with basic guidelines to modify that expression according to user’s need. Here we have given rules and some Test cases which is followed by the regular expression.

2. Rules for username

  • Must start with the alphabet
  • Only allow alphabet and _ (underscore)
  • Minimum 3 chars are requires

3. Regex for user name – ^([a-zA-Z])+([\\w]{2,})+$

  • If you want to allow any special characters in the user name then add that special char after \w like:
  • If you want to increase the minimum limit then replace that number-1 with 2 in expression
package main.java.com.javadeveloperzone.username;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UserNameRegx {
    public static final Pattern USER_NAME = Pattern.compile("^([a-zA-Z])+([\\w]{2,})+$");  //. represents single character
    public static void main(String[] args){
        System.out.println(isValidUserName("john"));                  // true
        System.out.println(isValidUserName("John1990"));              // true
        System.out.println(isValidUserName("john_Harry"));              // true
        System.out.println(isValidUserName("john_harry_1990"));               // true
        System.out.println(isValidUserName("john_HARRY"));     // true
        System.out.println(isValidUserName("jon"));     // true
        System.out.println(isValidUserName("_john"));     // false
        System.out.println(isValidUserName("john Harry"));     // false
        System.out.println(isValidUserName("12584_harry"));     // false
        System.out.println(isValidUserName("@_harry"));     // false
        System.out.println(isValidUserName("[email protected]_1990"));     // false
        System.out.println(isValidUserName("jo"));     // false
    public static boolean isValidUserName(String mobileNo){
        Matcher matcher = USER_NAME.matcher(mobileNo);
        return matcher.matches();

3. Conclusion

In this article, we have learned how we can use regular expression with java web development, As we all know that regular expression will work for the other languages as well so ^([a-zA-Z])+([\\w]{2,})+$ will also work for C#, JavaScript, Node and other languages as well to validate the username.

4. Source Code

5. References


Was this post helpful?


Leave a Reply

Your email address will not be published. Required fields are marked *