Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

javascript - The best way to match at least three out of four regex requirements

In password strategy, there are 4 requirements. It should contains any three of the following

  1. lower case.
  2. upper case.
  3. numeric.
  4. special character.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}$

Regular expression visualization

One-lined:

^(?:((?=.*d))((?=.*[a-z]))((?=.*[A-Z]))((?=.*[^a-zA-Z0-9]))|(?1)(?2)(?3)|(?1)(?2)(?4)|(?1)(?3)(?4)|(?2)(?3)(?4)).{4,8}$

Demo on Debuggex


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}$");    
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...