返回

正则表达式教程:大写字母、小写字母、数字、特殊符号任意 3 项密码

正则表达式

一、正则解释

/^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]/

这个正则表达式使用了一个负向前瞻断言,检查字符串是否不满足以下条件:

  • 仅包含大写字母
  • 仅包含大写字母和数字
  • 仅包含大写字母、数字和特殊符号
  • 仅包含小写字母
  • 仅包含小写字母和数字
  • 仅包含数字和特殊符号

如果字符串满足上述任何一个条件,则正则表达式不匹配。否则,字符串至少包含大写字母、小写字母、数字和特殊符号中的任意 3 项,正则表达式匹配。

二、使用场景

此正则表达式可用于验证密码,以确保密码足够安全。密码应该包含多种字符类型,以增加破解难度。

三、代码示例

JavaScript

const regex = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]/;

const password = "a1@";
console.log(regex.test(password)); // true

Java

import java.util.regex.Pattern;

public class PasswordValidator {

    public static boolean isValidPassword(String password) {
        Pattern pattern = Pattern.compile("^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]
import java.util.regex.Pattern;

public class PasswordValidator {

    public static boolean isValidPassword(String password) {
        Pattern pattern = Pattern.compile("^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]$");
        return pattern.matcher(password).matches();
    }

    public static void main(String[] args) {
        String password = "a1@";
        System.out.println(isValidPassword(password)); // true
    }
}
quot;
); return pattern.matcher(password).matches(); } public static void main(String[] args) { String password = "a1@"; System.out.println(isValidPassword(password)); // true } }

PHP

<?php

$regex = '/^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]/';

$password = 'a1@';
echo preg_match($regex, $password) ? 'true' : 'false'; // true
?>

Python

import re

regex = r"^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]
import re

regex = r"^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]$"

password = "a1@"
print(bool(re.match(regex, password))) # True
quot;
password = "a1@" print(bool(re.match(regex, password))) # True