Search code examples
pythonregexurlvimeo

Python regex extract vimeo id from url


embed_url = 'http://www.vimeo.com/52422837'
response = re.search(r'^(http://)?(www\.)?(vimeo\.com/)?([\/\d+])', embed_url)
return response.group(4)

The response is:

5

I was hoping for

52422837

Anybody an idea? I'm really bad with regexes :S


Solution

  • Use \d+ (no brackets) to match the literal slash + digits:

    response = re.search(r'^(http://)?(www\.)?(vimeo\.com/)?(\d+)', embed_url)
    

    Result:

    >>> re.search(r'^(http://)?(www\.)?(vimeo\.com/)?(\d+)', embed_url).group(4)
    '52422837'
    

    You were using a character group ([...]) where none was needed. The pattern [\/\d+] matches exactly one of /, + or a digit.