正则表达式以验证用户名

时间:2012-08-18 11:39:45

标签: java php html regex .htaccess

我正在尝试创建一个正则表达式来根据这些条件验证用户名:

  1. 仅包含字母数字字符, 下划线
  2. Underscore和dot不能位于 end 开始用户名(例如_username / username_ / .username / username.)。
  3. 下划线和点不能彼此相邻(例如user_.name)。
  4. Underscore或dot不能连续多次连续使用(例如user__name / user..name)。
  5. 字符数必须介于8到20之间。
  6. 这是我到目前为止所做的事情;听起来它强制执行所有标准规则但第5条规则。我不知道如何添加第五条规则:

     ^[a-zA-Z0-9]+([._]?[a-zA-Z0-9]+)*$
    

10 个答案:

答案 0 :(得分:156)

^(?=.{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

答案 1 :(得分:8)

Phillip的答案略有修改,修复了最新的要求

^[a-zA-Z0-9]([._](?![._])|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$

答案 2 :(得分:7)

我猜你必须在这里使用Lookahead表达式。 http://www.regular-expressions.info/lookaround.html

尝试

^[a-zA-Z0-9](_(?!(\.|_))|\.(?!(_|\.))|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$

[a-zA-Z0-9]字母数字那么(

_(?!\.) a _后面没有a。 OR

\.(?!_) a。没有后跟_ OR

[a-zA-Z0-9]字母数字)FOR

{6,18}最少6到最多18倍然后

[a-zA-Z0-9]字母数字

(第一个字符是alphanum,然后是6到18个字符,最后一个字符是alphanum,6 + 2 = 8,18 + 2 = 20)

答案 3 :(得分:1)

尽管我喜欢正则表达式,但我认为可读性是有限的

所以我建议

new Regex("^[a-z._]+$", RegexOptions.IgnoreCase).IsMatch(username) &&
!username.StartsWith(".") &&
!username.StartsWith("_") &&
!username.EndsWith(".") &&
!username.EndsWith("_") &&
!username.Contains("..") &&
!username.Contains("__") &&
!username.Contains("._") &&
!username.Contains("_.");

它更长,但不需要维护者打开expresso来理解。

当然你可以评论一个很长的正则表达式,但是那个读它的人必须依靠信任.......

答案 4 :(得分:1)

^ [A-Z0-9 _-] {3,15} $

^#行的开头

[a-z0-9_-]#匹配列表中的字符和符号,a-z,0-9,下划线,连字符

{3,15}#长度至少3个字符,最大长度15个

$#行结束

答案 5 :(得分:1)

private static final Scanner scan = new Scanner(System.in);

public static void main(String[] args) {
    int n = Integer.parseInt(scan.nextLine());
    while (n-- != 0) {
        String userName = scan.nextLine();
        String regularExpression = "^[[A-Z]|[a-z]][[A-Z]|[a-z]|\\d|[_]]{7,29}$";
        if (userName.matches(regularExpression)) {
            System.out.println("Valid");
        } else {
            System.out.println("Invalid");
        }
    }
}

答案 6 :(得分:0)

对不起,我是从我自己的库生成的,它使用的语法对Dart / Javascript / Java / Python有效,但无论如何,这里有:

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

我的图书馆代码:

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();

我的图书馆:https://github.com/thebinarysearchtree/RegExpBuilder

答案 7 :(得分:0)

这个应该可以解决问题:

if (Regex.IsMatch(text, @"
    # Validate username with 5 constraints.
    ^                          # Anchor to start of string.
    # 1- only contains alphanumeric characters , underscore and dot.
    # 2- underscore and dot can't be at the end or start of username,
    # 3- underscore and dot can't come next to each other.
    # 4- each time just one occurrence of underscore or dot is valid.
    (?=[A-Za-z0-9]+(?:[_.][A-Za-z0-9]+)*$)
    # 5- number of characters must be between 8 to 20.
    [A-Za-z0-9_.]{8,20}        # Apply constraint 5.
    $                          # Anchor to end of string.
    ", RegexOptions.IgnorePatternWhitespace))
{
    // Successful match
} else {
    // Match attempt failed
} 

答案 8 :(得分:0)

^(?=.{4,20}$)(?:[a-zA-Z\d]+(?:(?:\.|-|_)[a-zA-Z\d])*)+$

您可以测试正则表达式here

答案 9 :(得分:-1)

function isUserName(val){
    let regUser=/^[a-zA-Z0-9](_(?!(\.|_))|\.(?!(_|\.))|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$/;
    if(!regUser.test(val)){
      return 'Name can only use letters,numbers, minimum length is 8 characters';
    }
  }