Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regular expression for UserName with length range

I am writing a regular expression to validate UserName.

Here is the rule:

  • Length: 6 - 20 characters
  • Must start with letter a-zA-Z
  • Can contains a-zA-Z0-9 and dot(.)
  • Can't have 2 consecutive dots

Here is what I tried:

public class TestUserName {

    private static String USERNAME_PATTERN = "[a-z](\\.?[a-z\\d]+)+";
    private static Pattern pattern = Pattern.compile(USERNAME_PATTERN, CASE_INSENSITIVE);

    public static void main(String[] args) {
        System.out.println(pattern.matcher("user.name").matches()); // true
        System.out.println(pattern.matcher("user.name2").matches()); // true
        System.out.println(pattern.matcher("user2.name").matches()); // true

        System.out.println(pattern.matcher("user..name").matches()); // false
        System.out.println(pattern.matcher("1user.name").matches()); // false
    }
}

The pattern I used is good but no length constraint.

I tried to append {6,20} constraint to the pattern but It failed.

"[a-z](\\.?[a-z\\d]+)+{6,20}" // failed pattern to validate length

Anyone has any ideas?

Thanks!

like image 892
Loc Avatar asked Feb 07 '26 02:02

Loc


1 Answers

You can use a lookahead regex for all the checks:

^[a-zA-Z](?!.*\.\.)[a-zA-Z.\d]{5,19}$
  • Using [a-zA-Z.\d]{5,19} because we have already matched one char [a-zA-Z] at start this making total length in the range {6,20}
  • Negative lookahead (?!.*\.\.) will assert failure if there are 2 consecutive dots

Equivalent Java pattern will be:

Pattern p = Pattern.compile("^[a-zA-Z](?!.*\\.\\.)[a-zA-Z.\\d]{5,19}$");
like image 86
anubhava Avatar answered Feb 09 '26 16:02

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!