Search code examples
pythonregexspotify

Regex string to capture a track's Spotify URI or web link


I'm trying to integrate Spotify features on my Twitch chat-bot. All features of the bot is written in Python, using Spotipy.

One of them is, adding a song to my playing Spotify queue. Following code would work for that purpose.

if re.match(r"spotify[\/:]track[\/:].+[\s?]", songreq_params[1]):
   spotify.add_to_queue(songreq_params[1], sp_device_id)

But it seems to me that r"spotify[/:]track[/:].+[\s?]" regular expression doesn't work to catch Spotify track URIs and URLs such as:

I'm curious if the problem is about the snippet's syntax or the regex.


Solution

  • You can slightly modify the regex like this:

    import re
    a="spotify:track:3Mh4EaJcfM4v2hpY49rjg6"
    re.findall(r"spotify[/:]*track[/:]*[A-Za-z0-9]+",a)
    

    Do you also want to capture this link (https://open.spotify.com/track/3Mh4EaJcfM4v2hpY49rjg6?si=nFRVStM1TpCWWtaJGWNLsg)as well?

    Check out this regex this will probably help better. Let me know if this works. it covers both

    import re
    a="spotify:track:3Mh4EaJcfM4v2hpY49rjg6"
    b="https://open.spotify.com/track/3Mh4EaJcfM4v2hpY49rjg6?si=nFRVStM1TpCWWtaJGWNLsg"
    re.findall(r"[\bhttps://open.\b]*spotify[\b.com\b]*[/:]*track[/:]*[A-Za-z0-9?=]+",b)