【发布时间】:2019-05-23 00:55:37
【问题描述】:
我想了解下面的正则表达式并尝试在regex101 中测试它
^(?=.*[a-zA-Z])(?=.*[0-9]).{4,}$
【问题讨论】:
-
regex101中有解释部分
标签: regex regex-lookarounds regex-group regex-greedy
我想了解下面的正则表达式并尝试在regex101 中测试它
^(?=.*[a-zA-Z])(?=.*[0-9]).{4,}$
【问题讨论】:
标签: regex regex-lookarounds regex-group regex-greedy
那个正则表达式意义不大,可以缩短为:
.{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
【讨论】:
解释
^ # 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,}$ ...