用于自定义密码要求的正则表达式

Regex for custom password requirements

我试图根据密码 requirements.The 要求创建正则表达式

我创建了这个正则表达式

/^[0-9a-zA-Z\s!"#$\%&'\(\)\*\+\,\-\.\/\:;<=>?@\[\\]\^\_\`\{\|\}\~]+$/g

我对正则表达式了解不多,所以只需要确认它是正确的正则表达式还是需要更改。

How about this:

^(?=.{8,})(?=.*?\d)(?=.*[\s!\"#$\%&'\(\)\*\+\,\-\.\/\:;<=>?@\[\\]\^\_\`\{\|\}\~])(?=[a-zA-Z0-9].*?[a-zA-Z0-9].*?[a-zA-Z0-9].*?).*$

As seen here at regex101.com

解释:

I've used a lot of positive lookaheads, which you can read more about here

Basically, a forward lookahead ensures that some position has some characters in front of it. After checking if the start of the password is followed by all your conditions, we then match the password.
Think of it like this: You make sure everything is correct, and if it is, then you match the password. Otherwise you don't.

(?=.{8,}) checks if there are at least 8 characters
(?=.*?\d) checks if there is at least 1 digit
^(?=.{8,})(?=.*?\d)(?=.*[\s!\"#$\%&'\(\)\*\+\,\-\.\/\:;<=>?@\[\\]\^\_\`\{\|\}\~]) checks if there are at least 3 letters and/or numbers

你可以试试这个

^(?=.*\d)[ !"#$%&'()*+,.\/:;<=>?@[\]^`{|}~\w-]{8,}$


代码示例

const regex = /^(?=.*\d)[ !"#$%&'()*+,.\/:;<=>?@[\]^`{|}~\w-]{8,}$/gm;
const str = `1234
adnc
123456789
abcdefghij
ABCDEFGHIJ
1ABCDEFG
123-ANCNA
`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

PS:- 我已经用 [= 替换了模式中的 <code>\s 36=],如果你需要匹配所有类型的 space 字符,你可以再次将 </code> 替换为 <code>\s