Addev
Addev

Reputation: 32233

Regular Expression in Java for validating username

I'm trying the username chains in Java with following rules:

Could someone help me with the regular expression?

Upvotes: 6

Views: 26068

Answers (4)

sarkiroka
sarkiroka

Reputation: 1542

try this regular expression:

^[a-zA-Z0-9._-]{3,}$

Upvotes: 18

Jesse Walters
Jesse Walters

Reputation: 71

BTW, if there is an extra requirement: the starting letter of the username must be a character, you can write

try {
    if (subjectString.matches("\\b[a-zA-Z][a-zA-Z0-9\\-._]{3,}\\b")) {
        // Successful match 

    } else {
        // No match 

    }
} catch (PatternSyntaxException ex) {
    // Invalid regex 

}

Based on an example here.

Upvotes: 4

Emmanuel Bourg
Emmanuel Bourg

Reputation: 10988

What about:

    username.matches("[a-zA-Z0-9.\\-_]{3,}")

Upvotes: 1

Simone Gianni
Simone Gianni

Reputation: 11662

Sarkiroka solution is right, but forgot the dash and the point should be escaped.

You should add as \ to escape it, but mind that in Java the backslash is itself used to escape, so if you are writing the regex in a java file, you should write

String regex = "[a-zA-Z0-9\\._\\-]{3,}"; 

Note the double back slashes.

Upvotes: 5

Related Questions