使用帶括號正規表示式的 Regex.exec() 來提取字串的匹配項

有時你不想簡單地替換或刪除字串。有時你想要提取和處理匹配。這是一個如何操作匹配的示例。

什麼是匹配?當為字串中的整個正規表示式找到相容的子字串時,exec 命令會產生匹配。匹配是一個陣列,首先是匹配的整個子字串和匹配中的所有括號。

想象一下 html 字串:

<html>
<head></head>
<body>
  <h1>Example</h1>
  <p>Look a this great link : <a href="https://stackoverflow.com">Stackoverflow</a> http://anotherlinkoutsideatag</p>
  Copyright <a href="https://stackoverflow.com">Stackoverflow</a>
</body>

你想要提取並獲取 a 標記內的所有連結。首先,這裡是你寫的正規表示式:

var re = /<a[^>]*href="https?:\/\/.*"[^>]*>[^<]*<\/a>/g;

但是現在,想象一下你想要每個環節的 hrefanchor。你想要它在一起。你只需為每個匹配新增一個新的正規表示式,或者你可以使用括號:

var re = /<a[^>]*href="(https?:\/\/.*)"[^>]*>([^<]*)<\/a>/g; 
var str = '<html>\n    <head></head>\n    <body>\n        <h1>Example</h1>\n        <p>Look a this great link : <a href="https://stackoverflow.com">Stackoverflow</a> http://anotherlinkoutsideatag</p>\n\n        Copyright <a href="https://stackoverflow.com">Stackoverflow</a>\n    </body>\';\n';
var m;
var links = [];

while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    console.log(m[0]); // The all substring
    console.log(m[1]); // The href subpart
    console.log(m[2]); // The anchor subpart

    links.push({
      match : m[0],   // the entire match
      href : m[1],    // the first parenthesis => (https?:\/\/.*)
      anchor : m[2],  // the second one => ([^<]*)
    });
}

在迴圈結束時,你有一個與 anchorhref 的連結陣列,你可以用它來寫降價,例如:

links.forEach(function(link) {
  console.log('[%s](%s)', link.anchor, link.href);
});

更進一步:

  • 巢狀括號