6

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

  • Length >=3
  • Valid characters: a-z, A-Z, 0-9, points, dashes and underscores.

Could someone help me with the regular expression?

Delimitry
  • 2,987
  • 4
  • 30
  • 39
Addev
  • 31,819
  • 51
  • 183
  • 302

4 Answers4

18

try this regular expression:

^[a-zA-Z0-9._-]{3,}$
wisbucky
  • 33,218
  • 10
  • 150
  • 101
sarkiroka
  • 1,485
  • 20
  • 28
  • [a-zA-Z0-9_.-]{3,} is more accurate as he wants to include "points dashes and underscores". See http://stackoverflow.com/questions/3028642/regular-expression-for-letters-numbers-and – Grambot Jul 21 '11 at 20:41
  • 2
    @TheCapn: I fixed it as you were writing your comment. :-) – RichieHindle Jul 21 '11 at 20:43
  • 1
    You should add start `^` and end-of-string `$` anchors for validation regexes like these (although the Java `.matches()` method does do this implicitly). – ridgerunner Jul 21 '11 at 23:48
5

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.

Simone Gianni
  • 11,426
  • 40
  • 49
  • 2
    No need to escape `.`, and probably no need to escape `-` either since it's last in the class (but I'm unsure how Java handles this). – Qtax Jul 21 '11 at 21:33
4

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.

Jesse Walters
  • 71
  • 1
  • 5
1

What about:

    username.matches("[a-zA-Z0-9.\\-_]{3,}")
Emmanuel Bourg
  • 9,601
  • 3
  • 48
  • 76
  • 1
    I don't think you have to escape the .-_ characters if they're in the [] but other than that it looks fine, though you should've commented on Richie's answer before posting your own. – 8vius Jul 21 '11 at 20:47
  • 1
    The dash must be escaped, but it doesn't matter for the dot. – Emmanuel Bourg Jul 21 '11 at 20:55