Java regular expression to validate username

I am trying to use a username chain in Java with the following rules:

  • Length> = 3
  • Valid characters are: az, AZ, 0-9, periods, dashes, and underscores.

Can someone help me with regex?

+4
source share
4 answers

try this regex: ^ [A-Za-Z0-9 ._-] {3} $

+11
source

Sarkiroka's solution is correct, but forgot the dash, and the dot must be escaped.

You must add as \ to avoid this, but remember that in Java, the backslash itself is used to exit, so if you write a regular expression in a java file, you should write

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

Note the double backslash.

+5
source

BTW, if there is an additional requirement: the start 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 } 

See an example here .

+1
source

What about:

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

All Articles