Regular expression to validate username

后端 未结 10 955
温柔的废话
温柔的废话 2020-11-28 19:27

I\'m trying to create a regular expression to validate usernames against these criteria:

  1. Only contains alphanumeric characters, underscore an
相关标签:
10条回答
  • 2020-11-28 20:09

    A slight modification to Phillip's answer fixes the latest requirement

    ^[a-zA-Z0-9]([._](?![._])|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$
    
    0 讨论(0)
  • 2020-11-28 20:12

    Err sorry I generated this from my own library and it uses the syntax valid for Dart/Javascript/Java/Python, but anyway, here goes:

    (?:^)(?:(?:[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKlMNOPQRSTUVWXYZ0123456789]){1,1})(?!(?:(?:(?:(?:_\.){1,1}))|(?:(?:(?:__){1,1}))|(?:(?:(?:\.\.){1,1}))))(?:(?:(?:(?:[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKlMNOPQRSTUVWXYZ0123456789._]){1,1})(?!(?:(?:(?:(?:_\.){1,1}))|(?:(?:(?:__){1,1}))|(?:(?:(?:\.\.){1,1}))))){6,18})(?:(?:[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKlMNOPQRSTUVWXYZ0123456789]){1,1})(?:$)
    

    My library code:

    var alphaNumeric = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "l", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
    var allValidCharacters = new List.from(alphaNumeric);
    allValidCharacters.addAll([".", "_"]);
    
    var invalidSequence = (r) => r
      .eitherString("_.")
      .orString("__")
      .orString("..");
    
    var regex = new RegExpBuilder()
      .start()
      .exactly(1).from(alphaNumeric).notBehind(invalidSequence)
      .min(6).max(18).like((r) => r.exactly(1).from(allValidCharacters).notBehind(invalidSequence))
      .exactly(1).from(alphaNumeric)
      .end()
      .getRegExp();
    

    My library: https://github.com/thebinarysearchtree/RegExpBuilder

    0 讨论(0)
  • 2020-11-28 20:13
    ^(?=.{8,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$
     └─────┬────┘└───┬──┘└─────┬─────┘└─────┬─────┘ └───┬───┘
           │         │         │            │           no _ or . at the end
           │         │         │            │
           │         │         │            allowed characters
           │         │         │
           │         │         no __ or _. or ._ or .. inside
           │         │
           │         no _ or . at the beginning
           │
           username is 8-20 characters long
    

    If your browser raises an error due to lack of negative look-behind support, use the following alternative pattern:

    ^(?=[a-zA-Z0-9._]{8,20}$)(?!.*[_.]{2})[^_.].*[^_.]$
    
    0 讨论(0)
  • 2020-11-28 20:14

    ^[a-z0-9_-]{3,15}$

    ^ # Start of the line

    [a-z0-9_-] # Match characters and symbols in the list, a-z, 0-9, underscore, hyphen

    {3,15} # Length at least 3 characters and maximum length of 15

    $ # End of the line

    0 讨论(0)
提交回复
热议问题