Skip to content

How to validate a Username using Regular Expressions in Java

• Difficulty Level : Medium
• Last Updated : 16 Oct, 2020

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:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

• 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 “?”.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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
```

My Personal Notes arrow_drop_up