The Wayback Machine - https://web.archive.org/web/20240619072232/https://www.geeksforgeeks.org/how-to-validate-a-username-using-regular-expressions-in-java/
Open In App

How to validate a Username using Regular Expressions in Java

Last Updated : 16 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string str which represents a username, the task is to validate this username with the help of Regular Expressions.

A username is considered valid if all the following constraints are satisfied:

  • The username consists of 6 to 30 characters inclusive. If the username
    consists of less than 6 or greater than 30 characters, then it is an invalid username.
  • The username can only contain alphanumeric characters and underscores (_). Alphanumeric characters describe the character set consisting of lowercase characters [a – z], uppercase characters [A – Z], and digits [0 – 9].
  • The first character of the username must be an alphabetic character, i.e., either lowercase character
    [a – z]
    or uppercase character [A – Z].

Examples:

Input: str = “1Geeksforgeeks”
Output: False
Explanation:
The given username is invalid because it starts with a digit.

Input: str = “Geeksforgeeks_21”
Output: True
Explanation:
The given username satisfies all the conditions mentioned.

Input: str = “Geeksforgeeks?10_2A”
Output: False
Explanation:
The given username is invalid because it consists of invalid character “?”.

Approach: The idea is to use Regular Expressions to validate if the given username is valid or not. The following steps can be followed to compute the answer:

  1. Get the string.
  2. Form a regular expression to validate the given string. According to the conditions, the regular expression can be formed in the following way:
    regex = "^[A-Za-z]\\w{5, 29}$"
    

    Where:

    • “^” represents that starting character of the string.
    • “[A-Za-z]” makes sure that the starting character is in the lowercase or uppercase alphabet.
    • “\\w{5, 29}” represents a check to make sure that the remaining items are word items, which includes the underscore, until it reaches the end and that is represented with $.
    • The “{5, 29}” represents the 6-30 character constraint given to us minus the predefined first character.
  3. Match the string with the Regex. In Java, this can be done using Pattern.matcher().
  4. Return true if the string matches with the given regex, else return false.

Below is the implementation of the above approach:




// Java program to validate a username
// using Regular Expression or ReGex
  
import java.util.regex.*;
  
class GFG {
  
    // Function to validate the username
    public static boolean isValidUsername(String name)
    {
  
        // Regex to check valid username.
        String regex = "^[A-Za-z]\\w{5,29}$";
  
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
  
        // If the username is empty
        // return false
        if (name == null) {
            return false;
        }
  
        // Pattern class contains matcher() method
        // to find matching between given username
        // and regular expression.
        Matcher m = p.matcher(name);
  
        // Return if the username
        // matched the ReGex
        return m.matches();
    }
  
    // Driver Code
    public static void main(String[] args)
    {
  
        // Test Case: 1
        String str1 = "Geeksforgeeks";
        System.out.println(isValidUsername(str1));
  
        // Test Case: 2
        String str3 = "1Geeksforgeeks";
        System.out.println(isValidUsername(str3));
  
        // Test Case: 3
        String str5 = "Ge";
        System.out.println(isValidUsername(str5));
    }
}


Output:

true
false
false


Similar Reads

How to validate an IP address using Regular Expressions in Java
Given an IP address, the task is to validate this IP address with the help of Regular Expressions.The IP address is a string in the form "A.B.C.D", where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can't be greater than 3.Examples: Input: str = "000.12.12.034" Output: True Input: str =
3 min read
How to validate a Password using Regular Expressions in Java
Given a password, the task is to validate the password with the help of Regular Expression. A password is considered valid if all the following constraints are satisfied: It contains at least 8 characters and at most 20 characters.It contains at least one digit.It contains at least one upper case alphabet.It contains at least one lower case alphabe
3 min read
How to Validate a Password using Regular Expressions in Android?
Regular Expression basically defines a search pattern, pattern matching, or string matching. It is present in java.util.regex package. Java Regex API provides 1 interface and 3 classes. They are the following: MatchResult InterfaceMatcher classPattern classPatternSyntaxException class Pattern p = Pattern.compile(".e"); // represents single characte
4 min read
How to validate ISIN using Regular Expressions
ISIN stands for International Securities Identification Number. Given string str, the task is to check whether the given string is a valid ISIN(International Securities Identification Number) or not by using Regular Expression. The valid ISIN(International Securities Identification Number) must satisfy the following conditions: It Should be the com
6 min read
Validate Gender using Regular Expressions
Given some words of Gender, the task is to check if they are valid or not using regular expressions. The correct responses can be as given below: Male / male / MALE / M / mFemale / female / FEMALE / F / fNot prefer to say Example: Input: MOutput: True Input: SOutput: False Approach: The problem can be solved based on the following idea: Create a re
6 min read
Regular Expressions to Validate Google Analytics Tracking Id
Given some Google Analytics Tracking IDs, the task is to check if they are valid or not using regular expressions. Rules for the valid Tracking Id are: It is an alphanumeric string i.e., containing digits (0-9), alphabets (A-Z), and a Special character hyphen(-).The hyphen will come in between the given Google Analytics Tracking Id.Google Analytics
5 min read
Regular Expressions to Validate Provident Fund(PF) Account Number
Given some PF(Provident Fund) Account Number, the task is to check if they are valid or not using regular expressions. Rules for the valid PF Account Number are : PF account number is alphanumeric String and forward slaces.First five characters are reserved for alphabet letters.Next 17 characters are reserved for digits(0-9).It allows only special
5 min read
Regular Expressions to Validate ISBN Code
Given some ISBN Codes, the task is to check if they are valid or not using regular expressions. Rules for the valid codes are: It is a unique 10 or 13-digit.It may or may not contain a hyphen.It should not contain whitespaces and other special characters.It does not allow alphabet letters. Examples: Input: str = ”978-1-45678-123-4?Output: True Inpu
5 min read
Regular Expressions to validate Loan Account Number (LAN)
Given some Loan Account Number(LAN), the task is to check if they are valid or not using regular expressions. Rules for the valid Loan Account Number are: LAN is an alphanumeric string i.e., contains only digits (0-9) and uppercase alphabet characters.It does not allow whitespaces in it.It does not contain special characters.It starts with Uppercas
5 min read
Regular Expressions to Validate Account Office Reference Number
Given some Account Office Reference Number, the task is to check if they are valid or not using regular expressions. Rules for the valid Account Office Reference Number are: It is an alphanumeric string containing upper-case letters and digits.Accounts Office Reference Number is a unique, 13-character code.It starts with digits (0-9) and ends with
5 min read
Article Tags :
Practice Tags :