Regular expression to validate username

后端 未结 10 971
温柔的废话
温柔的废话 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: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

提交回复
热议问题