匹配至少四分之三的正则表达式要求的最佳方法 [英] The best way to match at least three out of four regex requirements
问题描述
在密码策略中,有 4 个要求.它应该包含以下任何三个
In password strategy, there are 4 requirements. It should contains any three of the following
- 小写.
- 大写.
- 数字.
- 特殊字符.
以下正则表达式将匹配所有情况
The following regex will match all cases
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{4,8}$
我知道我可以使用|"然而,声明所有组合将产生一个超长的正则表达式.替换'|'的最佳方法是什么以便它可以检查输入是否包含组合中的三个条件中的任何一个?
I know I can use '|' to declare all combinations, however, that will produce a supper long regex. What is the best way to replace '|' so that it can check if the input contains any of three conditions in the combination?
推荐答案
如果您使用的是 PCRE 风格,以下方案可以满足您的需求(格式化以提高可读性):
If you're using a PCRE flavor, the following one could suit your needs (formatted for readability):
^(?:
((?=.*\d))((?=.*[a-z]))((?=.*[A-Z]))((?=.*[^a-zA-Z0-9]))|
(?1) (?2) (?3) |
(?1) (?2) (?4) |
(?1) (?3) (?4) |
(?2) (?3) (?4)
).{4,8}$
单行:
^(?:((?=.*\d))((?=.*[a-z]))((?=.*[A-Z]))((?=.*[^a-zA-Z0-9]))|(?1)(?2)(?3)|(?1)(?2)(?4)|(?1)(?3)(?4)|(?2)(?3)(?4)).{4,8}$
关于 Debuggex
JavaScript regex 风格不支持递归(它实际上不支持很多东西).最好使用 4 个不同的正则表达式,例如:
JavaScript regex flavor does not support recursion (it does not support many things actually). Better use 4 different regexes instead, for example:
var validate = function(input) {
var regexes = [
"[A-Z]",
"[a-z]",
"[0-9]",
"[^a-zA-Z0-9]"
];
var count = 0;
for (var i = 0, n = regexes.length; i < n; i++) {
if (input.match(regexes[i])) {
count++;
}
}
return count >=3 && input.match("^.{4,8}$");
};
这篇关于匹配至少四分之三的正则表达式要求的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!