JavaScript中的正则表达式高级应用
字数 517 2025-11-08 20:56:56
JavaScript中的正则表达式高级应用
正则表达式是用于匹配字符串中字符组合的模式,在JavaScript中通过RegExp对象实现。下面我将详细讲解正则表达式的高级特性和应用场景。
1. 正则表达式基础回顾
- 字面量语法:
/pattern/flags - 构造函数:
new RegExp("pattern", "flags") - 常用标志符:
g:全局匹配i:不区分大小写m:多行匹配
2. 高级匹配模式
-
分组捕获:
const text = "2023-04-15"; const match = text.match(/(\d{4})-(\d{2})-(\d{2})/); console.log(match[1]); // "2023" - 年分组 console.log(match[2]); // "04" - 月分组 console.log(match[3]); // "15" - 日分组 -
非捕获分组
(?:...):// 只匹配但不捕获分组内容 const text = "hello world"; const match = text.match(/(?:hello) (world)/); console.log(match[1]); // "world" - 只有world被捕获
3. 零宽断言(Lookaround Assertions)
-
正向先行断言
(?=...):// 匹配后面跟着"元"的"5" const text = "5元, 10美元"; const result = text.match(/\d+(?=元)/g); console.log(result); // ["5"] -
负向先行断言
(?!...):// 匹配后面不是"元"的数字 const text = "5元, 10美元"; const result = text.match(/\d+(?!元)/g); console.log(result); // ["10"] -
正向后行断言
(?<=...):// 匹配前面是"$"的数字 const text = "价格$20, ¥30"; const result = text.match(/(?<=\$)\d+/g); console.log(result); // ["20"] -
负向后行断言
(?<!...):// 匹配前面不是"$"的数字 const text = "价格$20, ¥30"; const result = text.match(/(?<!\$)\d+/g); console.log(result); // ["30"]
4. 贪婪匹配与惰性匹配
-
贪婪匹配(默认):
const text = "<div>hello</div><div>world</div>"; const greedy = text.match(/<div>.*<\/div>/)[0]; // 匹配整个字符串:<div>hello</div><div>world</div> -
惰性匹配(使用
?):const text = "<div>hello</div><div>world</div>"; const lazy = text.match(/<div>.*?<\/div>/)[0]; // 只匹配第一个:<div>hello</div>
5. 反向引用
// 匹配重复的单词
const text = "hello hello world";
const result = text.match(/\b(\w+)\s+\1\b/g);
console.log(result); // ["hello hello"]
// 在替换中使用反向引用
const formatted = text.replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1");
console.log(formatted); // "04/15/2023"
6. 正则表达式的方法应用
-
test()方法:const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; console.log(emailRegex.test("test@example.com")); // true -
exec()方法(可迭代使用):const regex = /\w+/g; const text = "hello world"; let match; while ((match = regex.exec(text)) !== null) { console.log(`找到: ${match[0]} 位置: ${match.index}`); } // 找到: hello 位置: 0 // 找到: world 位置: 6
7. 实际应用场景
-
密码强度验证:
function checkPasswordStrength(password) { const strong = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/; const medium = /^(?=.*[a-zA-Z])(?=.*\d)[A-Za-z\d]{6,}$/; if (strong.test(password)) return "强"; if (medium.test(password)) return "中"; return "弱"; } -
URL解析:
function parseURL(url) { const regex = /^(https?):\/\/([^\/:]+)(?::(\d+))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/; const match = url.match(regex); return { protocol: match[1], hostname: match[2], port: match[3] || (match[1] === 'https' ? '443' : '80'), pathname: match[4] || '/', search: match[5] ? `?${match[5]}` : '', hash: match[6] ? `#${match[6]}` : '' }; }
8. 性能优化技巧
-
预编译正则表达式:
// 不好的做法:每次创建新正则 function validateEmail(email) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); } // 好的做法:预编译 const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; function validateEmail(email) { return emailRegex.test(email); } -
避免灾难性回溯:
// 危险的正则(可能引起灾难性回溯) const dangerous = /(a+)+b/; // 改进版本 const safe = /a+b/;
通过掌握这些高级特性,你可以编写更精确、更高效的正则表达式,解决复杂的字符串处理问题。