Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Regex for username with first character as alphabet and has particular range in Java?

I want to create a class in java for username validation using Regex. A username is considered valid if all the following constraints are satisfied:

  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 have tried an expression like:

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

This is giving me result as invalid for all usernames. I expect the output of Samantha_21 to be valid.

like image 592
Alexa Avatar asked Feb 03 '26 12:02

Alexa


1 Answers

Your regex has a typo and an omission. The typo is that the range limits should be separated by a comma. The omission is that you don't check the first character separately:

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

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

like image 84
Mad Physicist Avatar answered Feb 06 '26 00:02

Mad Physicist