【问题标题】:RegEx for Positive Lookahead - password rules (contains required numbers and characters)RegEx for Positive Lookahead - 密码规则(包含所需的数字和字符)
【发布时间】:2019-05-23 00:55:37
【问题描述】:

我想了解下面的正则表达式并尝试在regex101 中测试它

^(?=.*[a-zA-Z])(?=.*[0-9]).{4,}$

【问题讨论】:

  • regex101中有解释部分

标签: regex regex-lookarounds regex-group regex-greedy


【解决方案1】:

那个正则表达式意义不大,可以缩短为:

.{4,}$ // match at least 4 characters (or more) before ending

原因是 lookaheads 定义了匹配组模式 结束 的位置。但是您将前瞻放置在输入字符串的开头,在所有前瞻模式的前面捕获“”(无)。所以所有的 lookaheads 都是多余的。

所以:

^ 模式必须从输入的开头开始

(?=.*[a-zA-Z]) 查找任意数量的连续字母的前瞻(发现“TestPassword”,包含在匹配组中)

(?=.*[0-9]) 查找任意位数的前瞻(发现“1”,要包含在匹配组中)

如上所示,唯一匹配的是“TestPassword1”开头的“”。现在我们继续匹配...

.{4,}$ 现在匹配位于末尾的至少 4 个字符的任何内容 输入(找到“TestPassword1”,作为匹配组返回的)

证明和解释见以下代码:

let regex = /^(?=.*[a-zA-Z])(?=.*[0-9]).{4,}$/;
[match] = "TestPassword1".match(regex);
console.log(match); //TestPassword1

// just test for lookaheads result in matching an empty string at the start of input (before "T")
regex = /^(?=.*[a-zA-Z])(?=.*[0-9])/;
match = "TestPassword1".match(regex);
console.log(match); //[""]

// we're now testing for at least 4 characters of anything just before the end of input
regex = /.{4,}$/;
[match] = "TestPassword1".match(regex);
console.log(match); //TestPassword1

【讨论】:

    【解决方案2】:

    解释

     ^                        # BOS
     (?= .* [a-zA-Z] )        # Lookahead, must be a letter
     (?= .* [0-9] )           # Lookahead, must be a number
     .{4,}                    # Any 4 or more characters 
     $                        # EOS
    

    【讨论】:

    • 我知道结果。但我不明白positive lookahead 的规则。 regex1(?=regex2) 即首先搜索 regex1 并且如果存在 regex2。但是^(?=.*[a-zA-Z])(?=.*[0-9]).{4,}$ ...
    • 别担心,我们都去过那里,正则表达式并不容易,也不是一天就能掌握的。只要采取婴儿步骤,一次一步,你会变得越来越好。您可以从网络上的资源开始,例如 regexone.com
    • @greenb - 断言和其他非消耗构造,实际上并不存在于字符位置。它们存在于 个字符之间。这是我在 SO 上写过的一个主题,但我找不到它的链接。太糟糕了,也许你能找到它,它会帮助你永远了解这些鬼魂。
    • @sln 非常感谢。我从您的评论中了解到:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 2021-11-01
    • 2013-01-16
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多