Zonebit

个人的奋斗还是历史的进程?

View the Project on GitHub

24 November 2018

ECMAScript2018中的正则表达式命名组

by ganlyun

该特性在Chrome70中测试可用

基本命名组

在正则表达式中使用 (matches) 即为组匹配,而命名组的格式为 (?matches),通过使用命名组,正则库中的exec方法返回的类数组对象中的 groups 属性值将会从undefined变为一个包含所有命名组的对象,如下:

//before
var r=/(\d{4})-(\d{2})-(\d{2})/
var str='2015-04-13'
str.match(r)
// (4) ["2015-04-13", "2015", "04", "13", index: 0, input: "2015-04-13", groups: undefined]
//   0: "2015-04-13"
//   1: "2015"
//   2: "04"
//   3: "13"
//   groups: undefined
//   index: 0
//   input: "2015-04-13"
//   length: 4
//   __proto__: Array(0)

//after
var r=/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
var str='2015-04-13'
r.exec(str)
// (4) ["2015-04-13", "2015", "04", "13", index: 0, input: "2015-04-13", groups: {…}]
//   0: "2015-04-13"
//   1: "2015"
//   2: "04"
//   3: "13"
//   groups: {year: "2015", month: "04", day: "13"}
//   index: 0
//   input: "2015-04-13"
//   length: 4
//   __proto__: Array(0)

反向引用

一个非常棒的使用,在命名组之后的表达式中,可以使用 \k 的方式引用之前定义过的组匹配到的内容,例如

var sameword = /(?<fruit>apple|orange)==\k<fruit>/
sameword.test('apple==apple')   //true
sameword.test('orange==orange')   //true
sameword.test('apple==orange')  //false

在 String.prototype.replace 中使用命名组

命名组特性现在可以被用在 String 的 replace 实例方法中,我们可以轻松地交换字符串中的单词

例如,将“firstName lastName”更改为“lastName firstName”

var reg = /(?<firstname>[A-Za-z]+) (?<lastname>[A-Za-z]+)/
'gan lyun'.replace(reg,'$<lastname> $<firstname>') //注意此处参数语法格式

// "lyun gan"
tags: RegExp - 组匹配 - ECMAScript2018