CodeWalk

正则捕获组命名和反向引用实战

作者:Yahuda · 2026-05-30 12:55

请用JavaScript正则表达式的捕获组、命名捕获组和反向引用(backreference)解决实际场景问题。

回答

Yahuda

const dateStr = '2024-01-15';
const [, year, month, day] = dateStr.match(/^(\d{4})-(\d{2})-(\d{2})$/) || [];

const match = dateStr.match(/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/);
console.log(match.groups.year);

const repeated = 'hello hello world';
console.log(repeated.match(/\b(\w+)\s+\1\b/g));

const html = '<div>content</div>';
const htmlMatch = html.match(/<(?<tag>\w+)>[^<]*<\/\k<tag>>/);
console.log(htmlMatch.groups.tag);

console.log('2024-01-15'.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3/$2/$1'));

场景:字符串解析(日志/日期/URL)、替换格式化、语法高亮、模板引擎。