JavaScript 中的正则表达式(Regular Expression,简称 RegEx)是一种强大的文本处理工具,用于匹配、查找、替换等操作。下面是一些关于如何在 JavaScript 中使用正则表达式的介绍和示例。
创建正则表达式对象
你可以通过两种方式创建正则表达式:
-
字面量表示法:
const regex = /pattern/flags;
-
构造函数表示法:
const regex = new RegExp('pattern', 'flags');
其中 pattern
是要匹配的字符串模式,flags
是可选参数,用来指定正则表达式的标志位,如 i
表示不区分大小写,g
表示全局搜索等。
常用方法
1. test()
检查一个字符串是否与正则表达式匹配。
const regex = /hello/;
console.log(regex.test('hello world')); // 输出: true
2. exec()
执行一个匹配并返回第一个匹配的结果。
const regex = /hello/;
const result = regex.exec('hello world');
console.log(result); // 输出: ["hello", index: 0, input: "hello world", groups: undefined]
3. match()
字符串方法,用于查找第一个匹配的子串。
const str = 'hello world';
const match = str.match(/hello/);
console.log(match); // 输出: ["hello", index: 0, input: "hello world", groups: undefined]
4. search()
查找匹配项的位置。
const str = 'hello world';
const pos = str.search(/world/);
console.log(pos); // 输出: 6
5. replace()
替换匹配的子串。
const str = 'hello world';
const replaced = str.replace(/world/, 'JavaScript');
console.log(replaced); // 输出: "hello JavaScript"
6. split()
根据匹配项分割字符串。
const str = 'one,two,three';
const parts = str.split(',');
console.log(parts); // 输出: ["one", "two", "three"]
示例
假设我们想要找出字符串中的所有邮箱地址,我们可以这样做:
function findEmails(text) {
const emailRegex = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i;
return text.match(emailRegex);
}
const sampleText = "Contact us at support@example.com or sales@example.co.uk.";
const emails = findEmails(sampleText);
console.log(emails); // 输出: ["support@example.com", "sales@example.co.uk"]