Regular Expression in Java for validating username

后端 未结 4 2007
悲&欢浪女
悲&欢浪女 2021-01-12 20:24

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.
相关标签:
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.

    0 讨论(0)
  • 2021-01-12 21:06

    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.

    0 讨论(0)
  • 2021-01-12 21:08

    What about:

        username.matches("[a-zA-Z0-9.\\-_]{3,}")
    
    0 讨论(0)
  • 2021-01-12 21:10

    try this regular expression:

    ^[a-zA-Z0-9._-]{3,}$
    
    0 讨论(0)
提交回复
热议问题