Spotify 网址正则表达式

Spotify urls regex

我在使用 Regex 时遇到了一些问题。基本上我想做的是将这些类型的任何一种 spotify urls 用于播放列表

https://open.spotify.com/user/spotify/playlist/37i9dQZF1DZ06evO2ZpGiQ?si=-6S0EBlURrao__YyIOW6bg

spotify:user:spotify:playlist:37i9dQZF1DZ06evO2ZpGiQ

并获取 spotify 对于这些 URL 的用户 ID,并希望获取对于这些 URL 的 37i9dQZF1DZ06evO2ZpGiQ 的播放列表 ID

我还想要一些正则表达式来确保它是这些 URL 类型之一。

到目前为止,我已经尝试使用此正则表达式来检查它是否是 spotify url 使用此正则表达式:

^(spotify:|https:\/\/[a-z]+\.spotify\.com\/) 但它只匹配顶部 URL.

这很简单,只需使用字符 类。

工作示例:https://regex101.com/r/eQFWuR/1

正则表达式 spotify[\/:]playlist[\/:](.+)[\s?]

在这里,我得到每个候选字符串的不可变部分,即第一组中的 https://open.spotify.com/user/spotify/playlistspotify:user:spotify:playlist,然后我在第二组中捕获播放列表 ID,其余部分可以忽略。

你可以在那里看到它在工作:https://regex101.com/r/tDtsTS/1

^(https:\/\/open.spotify.com\/user\/spotify\/playlist\/|spotify:user:spotify:playlist:)([a-zA-Z0-9]+)(.*)$

对于您给出的示例,您还可以使用交替 | 匹配用户 ID 和播放列表 ID,仅在您还不想捕获值并捕获捕获组中的分隔符的第一部分([\/:])。然后你可以使用反向引用 </code></p> <p>那么用户名和播放列表可以参考同一个群号。用户名将在组 2 中,播放列表将在组 3 中。</p> <p><code>^(?:https:\/\/open\.spotify\.com|spotify)([\/:])user([^\/]+)playlist([a-z0-9]+)

详情

  • ^ 在行首声明位置
  • (?:非捕获组
    • https:\/\/open\.spotify\.com字面匹配(转义点\.字面匹配)
    • |
    • spotify 字面匹配
  • )关闭非捕获组
  • ([\/:]) 使用字符 class 在组中捕获 /: 以便它可以与对该组的反向引用一起使用(第 1 组)
  • user 匹配 user 后跟反向引用 </code></li> <li><code>([^\/]+) 使用取反字符 class 捕获用户 ID(组 2)而不是正斜杠
  • playlist 使用 2 个反向引用匹配播放列表(如 :playlist:/playlist/
  • ([a-z0-9]+) 正在捕获播放列表 id (group 3)

Regex demo

您可以使用不区分大小写的标志 /i 来匹配大小写字符。

const strings = [
  'https://open.spotify.com/user/spotify/playlist/37i9dQZF1DZ06evO2ZpGiQ?si=-6S0EBlURrao__YyIOW6bg',
  'spotify:user:spotify:playlist:37i9dQZF1DZ06evO2ZpGiQ'
];
let regex = /^(?:https:\/\/open\.spotify\.com|spotify)([\/:])user([^\/]+)playlist([a-z0-9]+)/gi;
strings.forEach((str) => {
  while ((m = regex.exec(str)) !== null) {
    if (m.index === regex.lastIndex) {
      regex.lastIndex++;
    }
    console.log("user id: " + m[2]);
    console.log("playlist id: " + m[3]);
  }
});