Positive Lookahead 的 RegEx - 密码规则(包含必需的数字和字符)
RegEx for Positive Lookahead - password rules (contains required numbers and characters)
我想了解下面的正则表达式并尝试在 regex101
中对其进行测试
^(?=.*[a-zA-Z])(?=.*[0-9]).{4,}$
已解释
^ # BOS
(?= .* [a-zA-Z] ) # Lookahead, must be a letter
(?= .* [0-9] ) # Lookahead, must be a number
.{4,} # Any 4 or more characters
$ # EOS
该正则表达式意义不大,可以缩短为:
.{4,}$ // match at least 4 characters (or more) before ending
原因是 前瞻 定义匹配组模式 结束 的位置。但是您将先行放置在输入字符串的开头,在所有先行模式前面捕获“”(无)。所以所有 前瞻性 都是多余的。
所以:
^
pattern must start at the beginning of input
(?=.*[a-zA-Z])
find lookahead of any number of consecutive alphabets (found "TestPassword", not to be included in matching group)
(?=.*[0-9])
find lookahead of any number of digits (found "1", not to be included in matching group)
Given above, the only match is "" at the beginning of "TestPassword1". Now we continue the matching...
.{4,}$
now match anything of at least 4 characters situated right at the end of
input (found "TestPassword1", which is returned as matching group)
证明和解释见下面的代码:
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
我想了解下面的正则表达式并尝试在 regex101
中对其进行测试^(?=.*[a-zA-Z])(?=.*[0-9]).{4,}$
已解释
^ # BOS
(?= .* [a-zA-Z] ) # Lookahead, must be a letter
(?= .* [0-9] ) # Lookahead, must be a number
.{4,} # Any 4 or more characters
$ # EOS
该正则表达式意义不大,可以缩短为:
.{4,}$ // match at least 4 characters (or more) before ending
原因是 前瞻 定义匹配组模式 结束 的位置。但是您将先行放置在输入字符串的开头,在所有先行模式前面捕获“”(无)。所以所有 前瞻性 都是多余的。
所以:
^
pattern must start at the beginning of input
(?=.*[a-zA-Z])
find lookahead of any number of consecutive alphabets (found "TestPassword", not to be included in matching group)
(?=.*[0-9])
find lookahead of any number of digits (found "1", not to be included in matching group)Given above, the only match is "" at the beginning of "TestPassword1". Now we continue the matching...
.{4,}$
now match anything of at least 4 characters situated right at the end of input (found "TestPassword1", which is returned as matching group)
证明和解释见下面的代码:
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