LHA
LHA

Reputation: 9655

Java regular expression for UserName with length range

I am writing a regular expression to validate UserName.

Here is the rule:

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!

Upvotes: 3

Views: 3552

Answers (4)

rock321987
rock321987

Reputation: 11032

This will also suffice (for only matching)

(?=^.{6,20}$)(?=^[A-Za-z])(?!.*\.\.)

For capturing, the matched pattern, you can use

(?=^.{6,20}$)(?=^[A-Za-z])(?!.*\.\.)(^.*$)

Upvotes: 1

Bohemian
Bohemian

Reputation: 424993

Use a negative look ahead to prevent double dots:

"^(?!.*\\.\\.)(?i)[a-z][a-z\\d.]{5,19}$"
  • (?i) means case insensitve (so [a-z] means [a-zA-Z])
  • (?!.*\\.\\.) means there isn't two consecutive dots anywhere in it

The rest is obvious.

See live demo.

Upvotes: 3

anubhava
anubhava

Reputation: 785068

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}$");

Upvotes: 4

Aaron
Aaron

Reputation: 24802

I would use the following regex :

^(?=.{6,20}$)(?!.*\.\.)[a-zA-Z][a-zA-Z0-9.]+$

The (?=.{6,20}$) positive lookahead makes sure the text will contain 6 to 20 characters, while the (?!.*\.\.) negative lookahead makes sure the text will not contain .. at any point.

Upvotes: 1

Related Questions