I found two useful javascript regex but none of them seems to be working right on Swift.
This works with a Youtube URL, but doesn't with Vimeo and DailyMotion. Both Vimeo & Dailymotion regex works on javascript.
Thanks guys.
** EDIT WITH THE SOLUTION **
Thanks GreatBigBore and Larme
private func getVendorId(_ regexStr:String, _ videoUrl:String, _ search:[Int]) -> String {
let regex = try? NSRegularExpression(pattern: regexStr, options: .caseInsensitive)
let result:[NSTextCheckingResult] = (regex?.matches(in: videoUrl, options: [], range: NSRange(location: 0, length: (videoUrl.characters.count ))))!
if result.count > 0 {
let groups = result.first!;
for i in search {
if (groups.rangeAt(i).length != 0) {
return (videoUrl as NSString).substring(with: groups.rangeAt(i))
}
}
}
return "";
}
override func viewDidLoad() {
let youtubeUrl = "https://www.youtube.com/watch?v=MCc0V5bgEF8";
let youtubeRegex = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)";
let youtubeId = getVendorId(youtubeRegex, youtubeUrl, [0]);
print("YOUTUBE ID -> \(youtubeId)")
let vimeoUrl = "https://player.vimeo.com/video/233459603";
let vimeoRegex = "https?:\\/\\/(?:www\\.|player\\.)?vimeo.com\\/(?:channels\\/(?:\\w+\\/)?|groups\\/([^\\/]*)\\/videos\\/|album\\/(\\d+)\\/video\\/|video\\/|)(\\d+)(?:$|\\/|\\?)";
let vimeoId = getVendorId(vimeoRegex, vimeoUrl, [2]);
print("VIMEO ID -> \(vimeoId)")
let dailyMotionUrl = "http://www.dailymotion.com/hub/x9q_Galatasaray";
let dailyMotionRegex = "^.+dailymotion.com\\/(video|hub)\\/([^_]+)[^#]*(#video=([^_&]+))?";
let dailyMotionId = getVendorId(dailyMotionRegex, dailyMotionUrl, [4, 2]);
print("DAILYMOTION ID -> \(dailyMotionId)")
super.viewDidLoad()
}