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

时间:2019-01-27 19:07:04

标签: javascript node.js regex

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

  • 最少3个字符

  • 最多20个字符

  • 最多1个下划线

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

我正在node.js 10.12.0版上运行。

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

List of some unit tests on regex101.com

4 个答案:

答案 0 :(得分:8)

您可以使用

^(?=^[^_]+_?[^_]+$)\w{3,20}$

请参见a demo on 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


这个问题已经引起了很多关注,因此我也想添加一个非正则表达式版本:

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

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

答案 1 :(得分:4)

可能是这样的:

height

积极的前瞻性确保长度至少为3个字符,最大为20个字符,我们会检查一个或多个字符之间的可选下划线。

尝试here –我也有added unit testing与您相似。


答案 2 :(得分:0)

如果您考虑同时使用JS functionsregex,这就是我的做法。

在比赛中,我通过忽略_条件来包括所有匹配的字符串,最后我要检查_条件。

let str = `_vila
v_v
v__v
v_v
vvvvvv_
12345678912345678912
12345678912345678912123456`


let matches = str.match(/^[a-z0-9]\w{1,18}[a-z0-9]$/gm)

let final = matches.map(e=> (e.split('_').length < 3 ? ({value:e,match:true}) : ({value:e,match:false})))

console.log(final)

答案 3 :(得分:0)

另一个变体:/^[a-z0-9](?:[a-z0-9]|_(?!.*_)){1,18}[a-z0-9]$/i