推荐答案
String.prototype.matchAll 是 JavaScript 中的一个方法,用于在字符串中查找所有与正则表达式匹配的结果,并返回一个迭代器。每个迭代结果都是一个包含匹配信息的数组,其中包括匹配的字符串、捕获组以及匹配的索引等详细信息。
本题详细解读
1. 方法定义
String.prototype.matchAll 方法接受一个正则表达式作为参数,并返回一个迭代器。这个迭代器会遍历字符串中所有与正则表达式匹配的结果。
const regex = /t(e)(st(\d?))/g; const str = 'test1test2'; const matches = str.matchAll(regex);
2. 返回值
matchAll 返回的迭代器中的每个元素都是一个数组,包含以下内容:
- 匹配的字符串:整个匹配的字符串。
- 捕获组:正则表达式中捕获组匹配的内容。
- 索引:匹配的字符串在原字符串中的起始位置。
- 输入字符串:原始字符串。
// www.javascriptcn.com code example
for (const match of matches) {
console.log(match);
}
// 输出:
// [
// 'test1',
// 'e',
// 'st1',
// '1',
// index: 0,
// input: 'test1test2',
// groups: undefined
// ]
// [
// 'test2',
// 'e',
// 'st2',
// '2',
// index: 5,
// input: 'test1test2',
// groups: undefined
// ]3. 正则表达式要求
传递给 matchAll 的正则表达式必须包含全局标志 g,否则会抛出 TypeError。
const regex = /t(e)(st(\d?))/; // 缺少全局标志 g const str = 'test1test2'; const matches = str.matchAll(regex); // TypeError: String.prototype.matchAll called with a non-global RegExp
4. 与 match 的区别
matchAll 与 String.prototype.match 的主要区别在于:
match返回一个数组,包含所有匹配的字符串,但不包含捕获组信息。matchAll返回一个迭代器,每个匹配结果都包含完整的匹配信息,包括捕获组和索引。
const regex = /t(e)(st(\d?))/g; const str = 'test1test2'; const matchResult = str.match(regex); console.log(matchResult); // ['test1', 'test2']
5. 使用场景
matchAll 适用于需要获取字符串中所有匹配结果及其详细信息的场景,特别是在处理复杂的正则表达式时,能够更方便地获取捕获组和匹配位置等信息。
const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g;
const str = '2023-10-05 and 2022-09-15';
for (const match of str.matchAll(regex)) {
console.log(match.groups);
}
// 输出:
// { year: '2023', month: '10', day: '05' }
// { year: '2022', month: '09', day: '15' }