具名捕获组
正则表达式具名捕获组
1. 具名捕获组基础
// 传统捕获组
const dateRegex = /(\d{4})-(\d{2})-(\d{2})/;
const match = '2026-06-14'.match(dateRegex);
console.log(match[1]); // '2026'
// 具名捕获组
const namedRegex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const namedMatch = '2026-06-14'.match(namedRegex);
console.log(namedMatch.groups.year); // '2026'
console.log(namedMatch.groups.month); // '06'
console.log(namedMatch.groups.day); // '14'
2. 与 replace 配合
// $<name> 替换
const result = '2026-06-14'.replace(
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/,
'$<day>/$<month>/$<year>'
);
console.log(result); // '14/06/2026'
// 替换函数
const formatted = '2026-06-14'.replace(
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/,
(...args) => {
const { year, month, day } = args.at(-1);
return `${year}年${parseInt(month)}月${parseInt(day)}日`;
}
);
3. 具名反向引用
// \k<name> 引用具名组
const duplicateWord = /\b(?<word>\w+)\s+\k<word>\b/gi;
const htmlTag = /<(?<tag>\w+)[^>]*>(?<content>[\s\S]*?)<\/\k<tag>>/g;
4. 实际应用
// URL 解析
const urlRegex =
/^(?<protocol>https?):\/\/(?<host>[^:/]+)(?::(?<port>\d+))?(?<path>\/[^?#]*)?(?:\?(?<query>[^#]*))?(?:#(?<fragment>.*))?$/;
// 模板引擎
function template(str, data) {
return str.replace(/\$\{(?<key>\w+)\}/g, (...args) => {
const { key } = args.at(-1);
return data[key] ?? '';
});
}