已命名捕获组(Named Capture Groups)
let re = /(\d{4})-(\d{2})-(\d{2})/
let result = re.exec('Pi day this year falls on 2021-03-14!')
result[0] // '2020-03-14', the complete match
result[1] // '2020', the first capture group
result[2] // '03', the second capture group
result[3] // '14', the third capture group
一直以来,正则表达式都能够支持已命名捕获组。这是一种通过引用名称、而非索引,来捕获各个组的方式。
目前,在ES9中,该功能已被JavaScript实现。正如下面的代码段所示,其结果对象包含了一个嵌套的组对象,其中每个捕获组的值都能够映射到其名称上。
let re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
let result = re.exec('Pi day this year falls on 2021-03-14!')
result.groups.year // '2020', the group named 'year'
result.groups.month // '03', the group named 'month'
result.groups.day // '14', the group named 'day'
而且,新的API与JavaScript的解构分配功能,也能够完美地结合在一起(请参见下面的代码段)。
let re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
let result = re.exec('Pi day this year falls on 2021-03-14!')
let { year, month, day } = result.groups
year // '2020'
month // '03'
day // '14'