本文介绍了4 个条件中的 2+ 个正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对用户密码有 4 个要求:

I have 4 requirements for user passwords:

  • 至少 1 个 a-z 字符
  • 至少 1 个 A-Z 字符
  • 至少 1 个 0-9 个字符
  • 中至少有 1 个符号.!@#$%^&*()_

但是,用户只需要满足 4 个条件中的 2+ 个.

However, user has to fulfill only 2+ of 4 conditions.

密码VVVV1111!234567AaAaAaAaA1!aA1!a有效,密码VVVVVVVV12345678aaaaaaa!!!!!!! 不是.

Passwords VVVV1111, !234567, AaAaAaAa or A1!aA1!a are valid, passwords VVVVVVVV, 12345678, aaaaaaa, !!!!!!! are not.

如何制作 2 of 4 OR regexp?

How can I make 2 of 4 OR regexp?

我想出了 3 个条件(A-Z、a-z 和 0-9):

I came up with this for 3 conditions (A-Z, a-z & 0-9):

^((?=.*?[A-Z])|(?=.*?[0-9]))((?=.*?[a-z])|((?=.*?[A-Z])(?=.*?[0-9]))).{8,30}$

但我认为必须有更好的选择,因为这个正则表达式在第四个条件下变得非常大.

But I think there has to be a better option because this regexp becomes really big with 4th condition.

推荐答案

总是把大问题分解成小问题.

Always break down big problems into smaller ones.

为您的四个不同条件中的每一个定义一个单独的正则表达式,然后检查是否满足了足够的条件.

Define a separate Regex for each of your four different conditions, then check if enough of them are fulfilled.

例如:

var checks = {
    lowercase: /[a-z]/,
    uppercase: /[A-Z]/,
    number: /[0-9]/,
    symbol: /[.!@#$%^&*()_]/
}, passcount = 0, results = {};
for( var k in checks) if( checks.hasOwnProperty(k)) {
    if( checks[k].test(password)) {
        passcount++;
        results[k] = true;
    }
    else results[k] = false;
}
if( passcount < 2) {
    alert("Your password didn't meet enough conditions.\n" +
      "[Provide useful info here - 'results' object lists " +
      "whether each test passed or failed, so use that for " +
      "a user-friendly experience!]");
    return false;
}
return true;

最后,强制性的 xkcd 漫画:

And finally, obligatory xkcd comic:

这篇关于4 个条件中的 2+ 个正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 15:55