分组
/(\d{4})-(\d{2})-(\d{2})/.test(‘2019-08-25‘) // true
RegExp.$1=‘2019‘
RegExp.$2=‘08‘
RegExp.$3=‘25‘
RegExp.$4=‘‘
RegExp.$_=‘2019-08-05‘
// 最多到RegExp.$9,没有$10,这本身是js的坑
// 解决:
‘2019-08-25‘.match(/(\d{4})-(\d{2})-(\d{2})/);
// 0: "2019-08-25"
// 1: "2019"
// 2: "08"
// 3: "25"
// groups: undefined
// index: 0
// input: "2019-08-25"
// length: 4
ES2018对正则(分组)的扩展:
‘2019-08-25‘.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/)
// 0: "2019-08-25"
// 1: "2019"
// 2: "08"
// 3: "25"
// groups: {year: "2019", month: "08", day: "25"}
// index: 0
// input: "2019-08-25"
// length: 4
引用
‘2019-08-25‘.match(/(\d{4})-(\d{2})-\2/)
// null
‘2019-08-08‘.match(/(\d{4})-(\d{2})-\2/)
// 不为null
// 最后一个 ‘\2‘ 是对第二个的引用
// ES2018引用
‘2019-08-25‘.match(/(?<year>\d{4})-(?<month>\d{2})-\k<month>/) // null
‘2019-08-08‘.match(/(?<year>\d{4})-(?<month>\d{2})-\k<month>/) // 不为null
‘2019-08-25‘.replace(/(\d{4})-(\d{2})-(\d{2})/,`year($1),month($2)`)
// "year(2019),month(08)"
// $1,$2是对前两个匹配字符串的引用
原文:https://www.cnblogs.com/jingouli/p/11427238.html