开发者

Regular Expression in Java for validating username

I'm trying the usern开发者_如何学编程ame 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?


try this regular expression:

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


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.


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.


What about:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜