Question

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?

Was it helpful?

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.

OTHER TIPS

Your own solution works fine, but time may come that Youtube decides to use video id that is not exactly 11 characters, this is an alternative solution for you:

local vidid = string.match(string, "%?v=(.-)&")

The pattern "%?v=(.-)&" matches a character ?, follows by v= and 0 or more characters after, then ends with &. The characters between v= and & are captured, note the use of - for non-greedy match.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top