Last active
March 10, 2016 06:51
-
-
Save DisappearPing/11f8c10f6946b31c770b to your computer and use it in GitHub Desktop.
String extension for getting Youtube id from URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
/* | |
this extension cover these case | |
www.youtube.com/v/id | |
www.youtube.com?v=vid | |
http://www.youtube.com/watch?v=id&feature=youtu.be | |
http://www.youtube.com/watch?v=id | |
youtube.be/id | |
http://www.youtube.com/watch?feature=player_detailpage&v=id#t=31s | |
www.youtube.com/watch?v=id&feature=youtu.be | |
www.youtube.com/watch?v=id | |
www.youtube.com/watch?feature=player_detailpage&v=id#t=31s | |
www.youtube.com/embed/id | |
from stackoverflow : http://stackoverflow.com/a/27796287 | |
ex: | |
let test = "https://www.youtube.com/embed/ZAF3u78Q9EM".parserYTIDFromURL() | |
console : | |
test = ZAF3u78Q9EM | |
*/ | |
extension String { | |
func parserYTIDFromURL() -> String { | |
let pattern = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)" | |
do{ | |
let regExp = try NSRegularExpression( pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive) | |
let array = regExp.matchesInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) | |
if array.count > 0{ | |
let result: NSTextCheckingResult = array.first! | |
return String((self as NSString).substringWithRange(result.range)) | |
} | |
}catch{ | |
return "" | |
} | |
return "" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment