比较实用(高大上)的正则表达式

匹配特殊字符集

[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]+

必须且只能是字母+数字的组合

长度6~25位
/^(?![a-zA-Z]+$)(?![0-9]+$)[a-zA-Z0-9]{6,25}$/

必须含有字母+数字的组合(还可以来些特殊字符)

长度6~25位
/^(?![a-zA-Z]+$)(?![0-9]+$)[a-zA-Z0-9\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]{6,25}$/

必须含有字母+数字+特殊字符的组合

长度6~25位
/^(?![a-zA-Z0-9]+$)(?![a-zA-Z\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]+$)(?![0-9\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]+$)[a-zA-Z0-9\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]{6,25}$/

正则语义解释

(?![a-zA-Z]+$) 从当前位置到结尾不能是纯字母
(?![0-9]+$)  从当前位置到结尾不能是纯数字
(?![\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]+$) 从当前位置到结尾不能是纯特殊字符

(?![a-zA-Z0-9]+$) 从当前位置到结尾不能只有字母和数字
(?![a-zA-Z\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]+$) 从当前位置到结尾不能只有字母和特殊字符
(?![0-9\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]+$) 从当前位置到结尾不能只有数字和特殊字符

[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E] 键盘上的特殊字符集

代码实例

用 php 实例演示下,可以用来做密码复杂度的验证,比如必须得是数字+字母的组合,必须得有特殊字符等要求。

<?php
// 必须是字母 数字的组合 不能有特殊字符
$pattern_must_char_num = '/^(?![a-zA-Z]+$)(?![0-9]+$)[a-zA-Z0-9]{6,25}$/';
// 不能是纯数字或纯字母 可以有特殊字符
$pattern_should_char_num = '/^(?![a-zA-Z]+$)(?![0-9]+$)[a-zA-Z0-9\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]{6,25}$/';
// 必须是字母 数字 特殊字符的组合
$pattern_must_char_num_spechar = '/^(?![a-zA-Z0-9]+$)(?![a-zA-Z\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]+$)(?![0-9\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]+$)[a-zA-Z0-9\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]{6,25}$/';

$pure_num = '123456';
$pure_char = 'asdqwe';
$char_num = 'asd123';
$char_num_spechar = '123@asd';

/**
 * 校验数据是否达到 pattern 的级别
 * @param  [type] $standard_pattern [description]
 * @param  [type] $subject          [description]
 * @return [type]                   [description]
 */
function complexity_check(string $standard_pattern, string $subject): bool
{
    // 匹配次数 > 0 则符合 pattern
    return preg_match($standard_pattern, $subject) > 0;
}

var_dump(complexity_check($pattern_must_char_num, $pure_num));
var_dump(complexity_check($pattern_must_char_num, $pure_char));
var_dump(complexity_check($pattern_must_char_num, $char_num));
var_dump(complexity_check($pattern_must_char_num, $char_num_spechar));
echo str_repeat("=", 20) . PHP_EOL;

var_dump(complexity_check($pattern_should_char_num, $pure_num));
var_dump(complexity_check($pattern_should_char_num, $pure_char));
var_dump(complexity_check($pattern_should_char_num, $char_num));
var_dump(complexity_check($pattern_should_char_num, $char_num_spechar));
echo str_repeat("=", 20) . PHP_EOL;

var_dump(complexity_check($pattern_must_char_num_spechar, $pure_num));
var_dump(complexity_check($pattern_must_char_num_spechar, $pure_char));
var_dump(complexity_check($pattern_must_char_num_spechar, $char_num));
var_dump(complexity_check($pattern_must_char_num_spechar, $char_num_spechar));

相关推荐