JavaScript中的正则表达式:完整指南与示例
正则表达式(regexp 或 regex)是用于搜索、替换和验证文本数据的强大工具。在JavaScript中,特别是在Node.js环境中,正则表达式被广泛使用:从日志处理和URL解析到表单验证和文本标记。在本文中,我们将介绍JavaScript中正则表达式的基础知识,讨论语法、方法,并提供Node.js的实用示例。
在JavaScript中创建正则表达式
在JavaScript中有两种创建正则表达式的方法:
- 字面量写法 — 最方便且最常用的方法:
/pattern/flags。 - RegExp构造函数 — 当模式是动态创建时使用:
new RegExp('pattern', 'flags')。
示例:
// 字面量写法const regexLiteral = /hello/i; // 标志 i — 忽略大小写
// RegExp构造函数const pattern = 'hello';const regexConstructor = new RegExp(pattern, 'i');
console.log(regexLiteral.test('Hello, world!')); // trueconsole.log(regexConstructor.test('HELLO')); // true基本标志(修饰符)
i— 忽略大小写(case-insensitive)。g— 全局搜索(查找所有匹配项,而不仅仅是第一个)。m— 多行模式(锚点^和$对每一行都有效)。s— “dotall”模式(点.包括换行符)。u— 完整Unicode支持。y— “sticky”模式(从当前位置搜索)。
JavaScript中的正则表达式方法
在JavaScript中,正则表达式与字符串方法以及RegExp本身的方法一起使用。
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')); // falseexec()方法
执行搜索并返回包含结果的数组或null。对于提取分组很有用。
const urlRegex = /https?:\\/\\/([^\\/]+)\\/(.*)/;const url = 'https://pythonlib.ru/regular-expressions';const match = urlRegex.exec(url);
if (match) { console.log('域名:', match[1]); // pythonlib.ru console.log('路径:', match[2]); // regular-expressions}与regexp一起使用的字符串方法
str.match(regex)— 返回匹配项的数组(或null)。str.matchAll(regex)— 返回所有匹配项(包含分组)的迭代器。str.replace(regex, replacement)— 替换匹配项。str.search(regex)— 返回第一个匹配项的索引(如果没有则为-1)。str.split(regex)— 根据正则表达式拆分字符串。
const text = '代码: 12345, 货号: ABC-6789';
// match — 查找所有数字const numbers = text.match(/\\d+/g);console.log(numbers); // ['12345', '6789']
// replace — 将连字符替换为冒号const cleaned = text.replace(/-/g, ':');console.log(cleaned); // '代码: 12345, 货号: ABC:6789'
// split — 按逗号和空格拆分const parts = text.split(/,\\s*/);console.log(parts); // ['代码: 12345', '货号: ABC-6789']基本模式和特殊字符
为了创建精确的模式,使用了元字符和量词。以下是最重要的几个: