Basically I have a Youtube URL as string, I want to extract the video Id from that URL. I found some code in objective c that is as below:
NSError *error = NULL;
Here is code to extract youtube video id from any youtube url: (Swift)
func extractYoutubeId(fromLink link: String) -> String {
let regexString: String = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)"
let regExp = try? NSRegularExpression(pattern: regexString, options: .caseInsensitive)
let array: [Any] = (regExp?.matches(in: link, options: [], range: NSRange(location: 0, length: (link.characters.count ))))!
if array.count > 0 {
let result: NSTextCheckingResult? = array.first as? NSTextCheckingResult
return (link as NSString).substring(with: (result?.range)!)
}
return ""
}
Some samples of Youtube's url:
let urls: [String] = [
"www.youtube-nocookie.com/embed/up_lNV-yoK4?rel=0",
"http://www.youtube.com/watch?v=peFZbP64dsU",
"http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel",
"http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player",
"http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player",
"http://youtu.be/6dwqZw0j_jY",
"http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_playe",
"http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player",
"http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player",
"http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player",
"http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0",
"http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY",
"1p3vcRhsY02"
]
My extension based on Islam Q. solution:
private extension String {
var youtubeID: String? {
let pattern = "((?<=(v|V|vi)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=vi=)|(?<=/u/[0-9_]/)|(?<=embed/))([\\w-]++)"
let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let range = NSRange(location: 0, length: count)
guard let result = regex?.firstMatch(in: self, range: range) else {
return count == 11 ? self : nil
}
let id = (self as NSString).substring(with: result.range)
return id.count == 11 ? id : nil
}
}