代码之家  ›  专栏  ›  技术社区  ›  Web User

用户名regex在检查长度时不工作

  •  3
  • Web User  · 技术社区  · 6 年前

    我试图根据下面的规则在Java中验证用户名:

    • 必须以小写字母(a-z)开头
    • 后面的字符可以是小写字母(a-z)或数字(0-9)
    • 只能使用一个符号,句点“.”,只能使用一次,并且不能位于用户名的开头或结尾。

    我用来执行验证的regex是 ^[a-z]+\.?[a-z0-9]+$

    这非常有效(可能有更好的方法),但现在我想允许用户名长度在3到10个字符之间。任何我想用的地方 {3,10} ,例如 ^([a-z]+\.?[a-z0-9]+){3,10}$ ,验证失败。我用的是优秀的 visual regex tool online regex tester .

    代码本身非常简单;我使用的是字符串类' matches 方法在Java 8中实现。 约翰·多伊 通过regex和长度验证,但是 多伊 没有。

    根据所选答案更新:

    鉴于正则表达式的复杂性,Java代码可能有点不言自明:

    private static final String PATTERN_USERNAME_REGEX = new StringBuilder()
        // the string should contain 3 to 10 chars
        .append("(?=.{3,10}$)")
        // the string should start with a lowercase ASCII letter
        .append("[a-z]")
        // then followed by zero or more lowercase ASCII letters or/and digits
        .append("[a-z0-9]*")
        // an optional sequence of a period (".") followed with 1 or more lowercase ASCII letters
        // or/and digits (that + means you can't have . at the end of the string and ? guarantees
        // the period can only appear once in the string)
        .append("(?:\\\\.[a-z0-9]+)?")
        .toString();
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   Wiktor Stribiżew    6 年前

    ^(?=.{3,10}$)[a-z][a-z0-9]*(?:\.[a-z0-9]+)?$
    

    s.matches("(?=.{3,10}$)[a-z][a-z0-9]*(?:\\.[a-z0-9]+)?")
    

    regex demo

    • ^ String#matches
    • (?=.{3,10}$)
    • [a-z]
    • [a-z0-9]*
    • (?:\.[a-z0-9]+)? . + ?
    • $