正規表達式筆記:群與反向參考(groups and backreferences)

總結

此篇是關於正規表達式「群(groups)」與「反向參考(backreferences)」的相關筆記。

筆記

文法

MDN 範例解讀

const personList = `First_Name: John, Last_Name: Doe
First_Name: Jane, Last_Name: Smith`;

const regexpNames = /First_Name: (\w+), Last_Name: (\w+)/gm;
const matchResults = [...personList.matchAll(regexpNames)];
for (const match of matchResults) {
  console.log(`Hello ${match[1]} ${match[2]}`);
  // Hello John Doe
  // Hello Jane Smith
}

說明:

執行 console.log 時可透過 match[1] 取出 First_Name 、透過 match[2] 取出 Last_name

補充說明:

const personList = `First_Name: John, Last_Name: Doe
First_Name: Jane, Last_Name: Smith`;

const regexpNames =
  /First_Name: (?<firstName>\w+), Last_Name: (?<lastName>\w+)/gm;
const matchResults = [...personList.matchAll(regexpNames)];
for (const match of matchResults) {
  console.log(`Hello ${match.groups.firstName} ${match.groups.lastName}`);
  // Hello John Doe
  // Hello Jane Smith
}

const quote = `Single quote "'" and double quote '"'`;
const regexpQuotes = /(['"]).*?\1/g;
for (const match of quote.matchAll(regexpQuotes)) {
  console.log(match[0]);
  // "'"
  // '"'
}

說明:

總結:尋找同為 '" 開頭+結尾的字串內容

可透過 \k<group-name> 來透過群名進行反向參考,範例如下:

const quote = `Single quote "'" and double quote '"'`;
const regexpQuotes = /(?<sign>['"]).*?\k<sign>/g;
for (const match of quote.matchAll(regexpQuotes)) {
  console.log(match[0], match.groups.sign);
  // "'" "
  // '"' '
}

const code = `function add(x, y) {
  return x + y;
}`;
const functionRegexp =
  /(function\s+)(?<name>[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*)/du;

const match = functionRegexp.exec(code);
console.info(match);
// ["function add", "function ", "add"]
// groups: { name: 'add' }
// index: 0
// indices: [[0, 12], [0, 9], [9, 12], groups: { name: [9, 12] } ]

const lines = code.split('\n');
lines.splice(
  1,
  0,
  ' '.repeat(match.indices[1][1] - match.indices[1][0]) +
    '^'.repeat(match.indices.groups.name[1] - match.indices.groups.name[0])
);
console.log(lines.join('\n'));
// function add(x, y) {
//          ^^^
//   return x + y;
// }

說明:

總結:印出原始字串第一行,於第二行印出「與功能名(含空格)等長的空白」,接著「印出與功能名等量的 ^ 符號」,最後再接著印完功能剩下的內容

參考文件