【问题标题】:Regex matching playlist id in spotify link正则表达式匹配Spotify链接中的播放列表ID
【发布时间】:2021-11-25 05:39:46
【问题描述】:

我需要从 Spotify 链接中提取播放列表 ID。链接可以有两种形式:

https://open.spotify.com/playlist/1GXN1gZMuTlW5LjpTNJF2q

https://open.spotify.com/playlist/1GXN1gZMuTlW5LjpTNJF2q?si=d3fa4293e26049f8

预期结果 => 1GXN1gZMuTlW5LjpTNJF2q

我尝试(?<=\/playlist\/)(.*)(?=\?|$) 来匹配 /playlist/ 和结尾或问号,但似乎无法正常工作。

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    您可以使用URL接口获取路径。

    new URL(uri).pathname.split('/').pop()
    

    const uri = 'https://open.spotify.com/playlist/1GXN1gZMuTlW5LjpTNJF2q?si=d3fa4293e26049f8';
    console.log(new URL(uri).pathname.split('/').pop());

    【讨论】:

      【解决方案2】:

      您的模式应该使用非贪婪量词(?<=\/playlist\/).*?(?=\?|$),但在这种情况下,您根本不需要任何环视。您可以使用捕获组来代替与除? 之外的任何字符匹配的否定字符类

      如果你只想匹配 spotify 链接,你可以让模式更具体

      \bhttps?:\/\/[^/]*\bspotify\.com\/playlist\/([^\s?]+)
      

      Regex demo

      或仅适用于open.spotify

      \bhttps?:\/\/open.spotify\.com\/playlist\/([^\s?]+)
      

      const regex = /\bhttps?:\/\/[^/]*\bspotify\.com\/playlist\/([^\s?]+)/;
      [
        "https://open.spotify.com/playlist/1GXN1gZMuTlW5LjpTNJF2q",
        "https://open.spotify.com/playlist/1GXN1gZMuTlW5LjpTNJF2q?si=d3fa4293e26049f8"
      ].forEach(s => {
        const m = s.match(regex);
        if (m) {
          console.log(m[1])
        }
      });

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-08
        • 1970-01-01
        • 2011-05-13
        • 2013-06-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多