我找到了两个有用的javascript正则表达式,但它们似乎都没有在Swift上运行。
这适用于Youtube网址,但不适用于Vimeo和DailyMotion。 Vimeo& Dailymotion正则表达式适用于javascript。
谢谢你们。
**编辑解决方案**
感谢GreatBigBore和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()
}
答案 0 :(得分:0)
你的正则表达式正常。问题是你没有考虑多个捕获组。您的变量result
将包含每个捕获组的NSRange
;您需要从其中一个获取已捕获的ID,而不是result?.range
。这是一些示例代码,向您展示我的意思。在getId()
之后将其添加到let result
功能:
print("Capture group count", result!.numberOfRanges)
for i in 0 ..< result!.numberOfRanges {
if result!.range(at: i).length == 0 {
print("Group \(i) is empty")
} else {
print("Group \(i) captured", (url as NSString).substring(with: result!.range(at: i)))
}
}
我不清楚为什么你的youtube id会以它的方式捕获;我认为它与所有后视镜头有关(我不是后视专家)。但问题不在于你的正则表达式;只需要从捕获组中获取您的ID,而不是直接从regRes.first
获取。