正则表达式(Regular Expression)是用于匹配字符串中字符组合的模式,在JavaScript中通过RegExp对象实现。主要应用于:
const regex = /pattern/flags;
const regex = new RegExp('pattern', 'flags');
| 元字符 | 说明 |
|---|---|
| \d | 匹配数字 |
| \w | 匹配字母数字下划线 |
| \s | 匹配空白符 |
| . | 匹配任意字符(除换行) |
| ^ | 匹配字符串开始 |
| $ | 匹配字符串结束 |
[abc] 匹配a、b或c
[^abc] 匹配非a、b、c的字符
[a-z] 匹配a到z范围内的字符
const regex = /hello/;
regex.test('hello world'); // true
const regex = /\d+/g;
regex.exec('2023 year'); // ['2023']
const emailRegex = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
const urlRegex = /https?:\/\/[\w\-\.]+(\/[\w\-\.]*)*/g;
掌握JavaScript正则表达式能极大提升文本处理效率,建议通过实际项目练习巩固这些知识。