1、組匹配
正則表達式使用圓括號進行組匹配,如:const RE_DATE = /(\d{4})-(\d{2})-(\d{2})/;
,三個圓括號形成了三個組匹配。
代碼:
const RE_DATE = /(\d{4})-(\d{2})-(\d{2})/;const matchObj = RE_DATE.exec('1999-12-31');
const year = matchObj[1]; // 1999
const month = matchObj[2]; // 12
const day = matchObj[3]; // 31
2、具名組匹配
ES2018 引入了具名組匹配(Named Capture Groups),允許為每一個組匹配指定一個名字,既便于閱讀代碼,又便于引用。
const RE_DATE = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;const matchObj = RE_DATE.exec('1999-12-31');
const year = matchObj.groups.year; // "1999"
const month = matchObj.groups.month; // "12"
const day = matchObj.groups.day; // "31"
上面代碼中,“具名組匹配”在圓括號內部,模式的頭部添加“問號 + 尖括號 + 組名”(?),然后就可以在exec方法返回結果的groups屬性上引用該組名。同時,數字序號(matchObj[1])依然有效。