用于匹配用户名的RegExp:最少3个字符,最多20个字符,字符之间可选的下划线

Jam*_*ark 7 javascript regex node.js

我正在尝试匹配roblox用户名(遵循这些指导原则):

  • 最少3个字符

  • 最多20个字符

  • 最多1个下划线

  • 下划线可能不在用户名的开头或结尾

我在node.js版本10.12.0上运行.

我当前的RegExp是: /^([a-z0-9])(\w)+([a-z0-9])$/i,但这不包括1个下划线的限制.

regex101.com上的一些单元测试列表

Jan*_*Jan 8

你可以用

^(?=^[^_]+_?[^_]+$)\w{3,20}$
Run Code Online (Sandbox Code Playgroud)

请参阅regex101.com上的演示(有用于演示目的的换行符)


细分这是

^         # start of the string
(?=
    ^     # start of the string
    [^_]+ # not an underscore, at least once
    _?    # an underscore
    [^_]+ # not an underscore, at least once
    $     # end of the string
 )
\w{3,20}  # 3-20 alphanumerical characters
$         # end
Run Code Online (Sandbox Code Playgroud)


这个问题引起了很多关注,所以我觉得还要添加一个非正则表达式版本:

let usernames = ['gt_c', 'gt', 'g_t_c', 'gtc_', 'OnlyTwentyCharacters', 'poppy_harlow'];

let alphanumeric = new Set(['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', '_']);

function isValidUsername(user) {
    /* non-regex version */
    // length
    if (user.length < 3 || user.length > 20)
        return false;

    // not allowed to start/end with underscore
    if (user.startsWith('_') || user.endsWith('_'))
        return false;
        
    // max one underscore
    var underscores = 0;
    for (var c of user) {
        if (c == '_') underscores++;
        if (!alphanumeric.has(c))
            return false;
    }

    if (underscores > 1)
        return false;
        
    // if none of these returned false, it's probably ok
    return true;
}

function isValidUsernameRegex(user) {
    /* regex version */
    if (user.match(/^(?=^[^_]+_?[^_]+$)\w{3,20}$/))
        return true;
    return false;
}

usernames.forEach(function(username) {
    console.log(username + " = " + isValidUsername(username));
});
Run Code Online (Sandbox Code Playgroud)

我个人认为正则表达式版本更短更清洁,但由您来决定.特别是字母数字部分需要一些比较或正则表达式.考虑到后者,您可以完全使用正则表达式版本.

  • 很好的简短解决方案,虽然我不确定OP的规则是否允许其他特殊字符而不是下划线,例如破折号或非ASCII. (2认同)
  • 此正则表达式不考虑没有下划线的用户名. (2认同)