1. 手机号验证
// 中国大陆手机号(11位数字,以1开头)
const phoneRegex = /^1[3-9]\d{9}$/;
console.log(phoneRegex.test("13800138000")); // true
console.log(phoneRegex.test("23800138000")); // false
2. 邮箱验证
// 通用邮箱格式验证
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailRegex.test("test@example.com")); // true
console.log(emailRegex.test("invalid.email")); // false
console.log(emailRegex.test("test@example..com")); // false
3. 密码强度验证
// 至少8个字符,包含大小写字母和数字
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
console.log(passwordRegex.test("Password123")); // true
console.log(passwordRegex.test("pass123")); // false (缺少大写字母)
console.log(passwordRegex.test("PASSWORD")); // false (缺少小写和数字)
4. URL验证
// 验证HTTP/HTTPS URL
const urlRegex = /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/;
console.log(urlRegex.test("https://example.com")); // true
console.log(urlRegex.test("ftp://invalid.com")); // false
console.log(urlRegex.test("example.com")); // false (缺少协议)
5. 身份证号码验证
// 18位身份证号码(含校验位)
const idCardRegex = /^\d{17}[\dXx]$/;
console.log(idCardRegex.test("110101199001011234")); // true
console.log(idCardRegex.test("11010119900101123x")); // true
console.log(idCardRegex.test("11010119900101123")); // false (只有17位)
6. IP地址验证
// IPv4地址验证
const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
console.log(ipRegex.test("192.168.1.1")); // true
console.log(ipRegex.test("256.0.0.1")); // false (超出范围)
console.log(ipRegex.test("192.168.1")); // false (格式错误)
7. 日期格式验证(YYYY-MM-DD)
const dateRegex = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/;
console.log(dateRegex.test("2023-05-15")); // true
console.log(dateRegex.test("2023-13-01")); // false (月份超出范围)
console.log(dateRegex.test("2023/05/15")); // false (分隔符错误)
8. HTML标签提取
// 提取HTML标签(如<a href="#">链接</a>)
const htmlTagRegex = /<[^>]+>/g;
const html = "<p>Hello <a href='#'>world</a></p>";
console.log(html.match(htmlTagRegex)); // ['<p>', '<a href="#">', '</a>', '</p>']
9. 去除字符串中的空格
// 去除所有空格
const noSpaceRegex = /\s/g;
const str = " Hello World! ";
console.log(str.replace(noSpaceRegex, "")); // "HelloWorld!"
// 去除首尾空格(ES5+可用.trim())
const trimRegex = /^\s+|\s+$/g;
console.log(str.replace(trimRegex, "")); // "Hello World!"
10. 提取数字
// 从字符串中提取所有数字
const numberRegex = /\d+/g;
const text = "价格:199元,数量:3个";
console.log(text.match(numberRegex)); // ['199', '3']
正则表达式标志
JavaScript 正则表达式支持以下标志:
g
:全局匹配(查找所有匹配项,而不是找到第一个后停止)i
:忽略大小写m
:多行匹配模式u
:Unicode模式,正确处理大于\uFFFF的Unicode字符y
:粘连模式,仅从lastIndex位置开始匹配
使用建议
- 测试正则表达式:在实际使用前,建议使用工具(如RegExr)测试正则表达式的匹配效果。
- 转义特殊字符:在正则表达式中,某些字符(如
.
,*
,+
,?
,^
,$
等)有特殊含义,如果需要匹配这些字符本身,需要使用反斜杠转义(如\.
匹配点号)。 - 性能注意事项:复杂的正则表达式可能会影响性能,尤其是在处理大量文本时。
正则表达式是一个强大但复杂的工具,掌握常用模式可以大大提高字符串处理效率。