常用正则速查

220 阅读1分钟

不定时整理一下项目中常用到的一些正则判断,跟大家分享,同时也方便自己查找。

1. 密码强弱判断(8-24位无符号版)

// 强
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]{8,24}$/

// 中
/^(?=.*[a-z])(?=.*[A-Z])|(?=.*[A-Z])(?=.*[0-9])|(?=.*[a-z])(?=.*[0-9])[a-zA-Z0-9]{8,24}$/

// 弱
/^(?=.*[a-z])|(?=.*[A-Z])|(?=.*[0-9])[a-zA-Z0-9]{8,24}$/

2. 匹配特殊字符

/[`~!@#$^&*()=|{}':;',\\\[\]\.<>\/?~!@#¥……&*()——|{}【】';:""'。,、?\s]/g

3. 匹配手机号、邮箱

// 手机号
Number(value.slice(0, 1)) === 1 && /^([0-9]){1,11}$/.test(value) && value.length === 11
// 邮箱
value.slice(0, 1) !== "-" && /^([a-zA-Z0-9]?)([a-zA-Z0-9\-])+@([a-zA-Z0-9])+\.[a-zA-Z]{2,4}$/.test(value)
  • 案例:登录框判断邮箱或手机号
if ((Number(value.slice(0, 1)) === 1) && /^([0-9]){1,11}$/.test(value) && value.length === 11) {
    this.loginType = "phone";
    this.userRight = true;
} else if (value.slice(0, 1) !== "-" && /^([a-zA-Z0-9]?)([a-zA-Z0-9\-])+@([a-zA-Z0-9])+\.[a-zA-Z]{2,4}$/.test(value)) {
    this.loginType = "email";
    this.userRight = true;
}

4. 匹配价格框

<input type="text" id="price-min" min="0"> -
<input type="text" id="price-max" min="0">
  • 在输入框的监听函数中使用(暂未做节流处理)
// 获取最新输入的值
let lastStr = e.target.value[e.target.value.length - 1];

if (/^0/.test(e.target.value) || e.originalEvent.inputType !== "deleteContentBackward" && !/\d/.test(lastStr)){
    setTimeout( _ => e.target.value = e.target.value.replace(lastStr, ""), 150 );
}

5. 匹配中文新姿势

/\p{Script=Han}/ug

// 使用
const str = '你好,世界';
const reg = /\p{Script=Han}/ug;
reg.test(str); // true
str.match(reg); // ["你", "好", "世", "界"]