exec方法返回含匹配字符串、捕获组、index、input及groups属性的数组,支持位置和命名捕获组提取,并在全局模式下通过lastindex实现多次匹配。

exec 方法是 JavaScript 中正则表达式对象的原生方法,它不仅返回匹配结果,还能完整暴露所有捕获组(包括命名捕获组和索引捕获组)的详细信息,比 match 更适合需要精确控制匹配过程的场景。
返回值结构:不只是匹配字符串
exec 成功匹配时返回一个数组,该数组具备额外属性:
- 索引 0:完整匹配的字符串
-
索引 1, 2, …:按左括号出现顺序排列的**位置捕获组**内容(未匹配则为
undefined) -
.index:本次匹配在原字符串中的起始下标 -
.input:原始输入字符串 -
.groups(仅当使用命名捕获组(?<name>...)</name>时存在):一个对象,键为组名,值为对应捕获内容
获取位置捕获组:按索引访问
例如提取日期中的年、月、日:
const re = /(\d{4})-(\d{2})-(\d{2})/;
const str = "今天是2023-05-20";
const result = re.exec(str); // → ["2023-05-20", "2023", "05", "20"]
if (result) {
console.log("全匹配:", result[0]); // "2023-05-20"
console.log("年:", result[1]); // "2023"
console.log("月:", result[2]); // "05"
console.log("日:", result[3]); // "20"
console.log("起始位置:", result.index); // 4("2023" 的 '2' 在字符串中索引为 4)
}
获取命名捕获组:通过 .groups 对象
使用 (?<name>...)</name> 语法后,可直接用名字取值:
const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const result = re.exec("会议时间:2024-12-01");
if (result) {
console.log(result.groups.year); // "2024"
console.log(result.groups.month); // "12"
console.log(result.groups.day); // "01"
// .groups 是普通对象,支持解构
const { year, month, day } = result.groups;
}</day></month></year>
注意全局标志 g 和 lastIndex
带 g 标志时,exec 会“记住”上次匹配结束位置(lastIndex),连续调用可遍历全部匹配。但需手动重置 lastIndex = 0 才能重新开始:
const re = /\b\w+\b/g; // 匹配单词 const str = "hello world test"; console.log(re.exec(str)); // ["hello"] console.log(re.exec(str)); // ["world"] console.log(re.exec(str)); // ["test"] console.log(re.exec(str)); // null(已到末尾) re.lastIndex = 0; // 重置后可再次从头匹配 console.log(re.exec(str)); // ["hello"]
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











