V8实现了正则命名分组功能
const RE_DATE = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const matchObj = RE_DATE.exec('2018-06-07');
const year = matchObj.groups.year; // 2018
const month = matchObj.groups.month; // 06
const day = matchObj.groups.day; // 07
const RE_TWICE = /^(?<word>[a-z]+)!\k<word>$/;
RE_TWICE.test('hello!hello'); // true
RE_TWICE.test('hello!word'); // false
等同于
const RE_TWICE = /^(?<word>[a-z]+)!\1$/;
RE_TWICE.test('hello!hello'); // true
RE_TWICE.test('hello!word'); // false
const RE_DATE = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
console.log('2018-06-07'.replace(RE_DATE,
'$<month>/$<day>/$<year>'));
// 06/07/2018
. 如果可选的命名组不被匹配,则其属性值被设置为undefined,但key是仍存在
. 分组名不能有重复项
评论