Java – What is a regular expression for usernames whose first character is a letter and has a specific range in Java?

What is a regular expression for usernames whose first character is a letter and has a specific range in Java?… here is a solution to the problem.

What is a regular expression for usernames whose first character is a letter and has a specific range in Java?

I want to create a class in java for username validation using Regex. The user name is considered valid if all of the following constraints are met:

  1. The username consists of 8 to 30 characters inclusive. If the username consists of less than or greater than characters, then it is an invalid username.
  2. 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].
  3. The first character of the username must be an alphabetic character, i.e., either lowercase character [a-z] or uppercase character [A-Z].

I’ve tried this expression:

^[a-zA-Z0-9_]{8-30}$

This gives me the result that it is invalid for all usernames. I want the output of Samantha_21 to be valid.

Solution

Your regular expression has typos and omissions. The typo is that the range limit should be separated by commas. What’s missing is that you didn’t check the first character separately :

^[a-zA-Z][a-zA-Z0-9_]{7,29}$

The range is reduced by one to accommodate the fixed first character.

Related Problems and Solutions