java Java中用于验证用户名的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6782437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:15:04  来源:igfitidea点击:

Regular Expression in Java for validating username

javaregexvalidation

提问by Addev

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

我正在尝试使用以下规则在 Java 中使用用户名链:

  • Length >=3
  • Valid characters: a-z, A-Z, 0-9, points, dashes and underscores.
  • 长度 >=3
  • 有效字符:az、AZ、0-9、点、破折号和下划线。

Could someone help me with the regular expression?

有人可以帮我处理正则表达式吗?

回答by sarkiroka

try this regular expression:

试试这个正则表达式:

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

回答by Simone Gianni

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

Sarkiroka 解决方案是正确的,但忘记了破折号,应该转义点。

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

您应该添加为 \ 来转义它,但请注意在 Java 中反斜杠本身用于转义,因此如果您在 java 文件中编写正则表达式,您应该编写

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

Note the double back slashes.

注意双反斜杠。

回答by Jesse Walters

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

BTW,如果有额外要求:用户名的起始字母必须是字符,可以这样写

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.

基于此处的示例。

回答by Emmanuel Bourg

What about:

关于什么:

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