JS正则表达式进阶:断言、分组与性能优化
深入学习正则表达式的高级特性,包括前瞻/后顾断言、捕获与非捕获分组、回溯控制以及性能优化技巧。 · 难度:入门 · +15XP
正则表达式进阶
掌握基础正则后,这些高级特性将让你处理字符串更加得心应手。
1. 断言(Assertions)
断言用于匹配位置而非字符。
| 类型 | 语法 | 示例 |
|---|---|---|
| 正向先行断言 | (?=...) | \d(?=px) 匹配后跟 px 的数字 |
| 负向先行断言 | (?!...) | \d(?!px) 匹配后不跟 px 的数字 |
| 正向后顾断言 | (?<=...) | (?<=\$)\d+ 匹配 $ 后的数字 |
| 负向后顾断言 | (? | (? 匹配非 $ 后的数字 |
2. 分组与反向引用
// 捕获分组
const regex = /(\w+)\s\1/; // 匹配重复单词
console.log("hello hello".match(regex)); // ["hello hello", "hello"]
// 非捕获分组 (?:...)
const nonCapture = /(?:https?:\/\/)?(\w+\.\w+)/;
console.log("https://example.com".match(nonCapture));
// 命名分组 (ES2018)
const named = /(?<year>\d{4})-(?<month>\d{2})/;
const result = "2024-03".match(named);
console.log(result.groups.year); // "2024"
3. 贪婪与懒惰匹配
const str = "<div>内容</div><span>其他</span>";
// 贪婪模式(默认):尽可能多匹配
console.log(str.match(/<.+>/)); // "<div>内容</div><span>其他</span>"
// 懒惰模式:尽可能少匹配
console.log(str.match(/<.+?>/)); // "<div>"
4. 性能优化建议
- 避免使用
.*,尽量用具体字符类。 - 使用非捕获分组
(?:...)替代捕获分组当不需要引用时。 - 将正则对象移出循环,避免重复创建。
- 使用
test()替代match()仅检查是否存在。 - 对于复杂匹配,考虑拆分为多个简单正则。
练习提示
修改 starter_code 中的正则表达式,尝试匹配所有以 .jpg 结尾的 URL,或提取 HTML 标签内的文本内容。