Search code examples
stringlualua-patterns

How to extract youtube video id from a URL in Lua


I need to extract youtube video id (e.g., brSU-lAACiA) from URL below that is in a Lua string variable.

local string = "a:2:{s:8:\"td_video\";s:60:\"http:\/\/www.youtube.com\/watch?v=brSU-lAACiA&feature=autoshare\";s:13:\"td_last_video\";s:60:\"http:\/\/www.youtube.com\/watch?v=brSU-lAACiA&feature=autoshare\";}"

What should be the pattern?


Solution

  • I think I got it.

    local string = "a:2:{s:8:\"td_video\";s:60:\"http:\/\/www.youtube.com\/watch?v=brSU-lAACiA&feature=autoshare\";s:13:\"td_last_video\";s:60:\"http:\/\/www.youtube.com\/watch?v=brSU-lAACiA&feature=autoshare\";}"
    
    pattern = "v=(...........)"
    
    local vidid =   string.match(string, pattern)
    

    There are 11 dots because Youtube video ID are only 11 characters. I'm not expert in making these patterns, so if there are other easier and shorter methods please share them with me.