JavaScript正则表达式实例详解:实战应用
正则表达式(RegExp)是用于字符串搜索、替换和验证的强大工具。在JavaScript和Node.js中,它们被广泛应用于表单验证、日志解析等场景。本文将讲解基础语法、常用方法,并解决几个实战问题。
1. 创建正则表达式
在JavaScript中,有两种创建正则表达式的方式:
- 字面量写法(推荐):
/pattern/flags - 构造函数
new RegExp('pattern', 'flags')
示例:
// 字面量写法const regexLiteral = /hello/i;
// 构造函数(适用于动态模式)const pattern = 'hello';const regexConstructor = new RegExp(pattern, 'i');
console.log(regexLiteral.test('Hello World')); // trueconsole.log(regexConstructor.test('HELLO')); // true2. RegExp和String的常用方法
在JavaScript中处理正则表达式有两种类型的方法:RegExp对象的方法和字符串的方法。
2.1 test()方法
检查字符串中是否存在匹配项。返回true或false。
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;console.log(emailRegex.test('user@example.com')); // trueconsole.log(emailRegex.test('invalid-email')); // false2.2 exec()方法
查找匹配项并返回包含详细信息的数组(或null)。适用于提取数据。
const str = '价格:1500元,折扣:200元';const priceRegex = /(\\d+)/g;let match;
while ((match = priceRegex.exec(str)) !== null) { console.log(`找到数字:${match[1]}`);}// 输出:// 找到数字:1500// 找到数字:2002.3 字符串的match()方法
与exec()类似,但从字符串调用。
const text = 'JavaScript太棒了!JS无处不在。';const result = text.match(/JS/g);console.log(result); // [ 'JS', 'JS' ]2.4 字符串的replace()方法
将匹配项替换为指定字符串或函数结果。
const phone = '+7 (123) 456-78-90';const cleaned = phone.replace(/[\\s\\-\\(\\)\\+]/g, '');console.log(cleaned); // 71234567890
// 使用捕获组进行替换const date = '2024-03-15';const formatted = date.replace(/(\\d{4})-(\\d{2})-(\\d{2})/, '$3.$2.$1');console.log(formatted); // 15.03.20242.5 字符串的search()方法
返回第一个匹配项的索引,或-1。
const sentence = '在PythonLib学习JavaScript';const index = sentence.search(/javascript/i);console.log(index); // 63. 标志和特殊字符:实战示例
标志用于改变搜索行为。最常用的标志:
g— 全局搜索(查找所有匹配项,而非第一个)。i— 不区分大小写搜索。m— 多行模式(锚点^和$作用于每一行)。
使用m标志的示例:
const multiLineText = `第一行第二行第三行`;
// 不使用m标志console.log(multiLineText.match(/^第二行/)); // null
// 使用m标志console.log(multiLineText.match(/^第二行/m)); // [ '第二行' ]常用特殊字符
| 字符 | 描述 |
|---|