import Foundation
let pattern = #"(?:(.*)(?:https:|http:)?\/\/)?(?:(.*)(?:www\.youtube\.com\/(?:embed\/|watch\?v=)|youtu\.be\/|youtube\.googleapis\.com\/v\/)(?<YoutubeID>[a-z0-9-_]{11,12})|(?:vimeo\.com\/|player\.vimeo\.com\/video\/)(?<VimeoID>[0-9]+))"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive])
let testString = #"""
https://www.youtube.com/embed/123456789012
https://www.youTUbe.com/embed/123456789012
http://www.youtube.com/watch?v=My2FRPA3Gf8
htTp://www.youtube.com/watch?V=My2FRPA3Gf8
http://youtu.be/My2FRPA3Gf8
http://youTU.be/My2FRPA3Gf8
https://www.youtu.be/embed/123456789012
https://youtube.googleapis.com/v/123456789012
https://youtube.googleAPis.com/v/123456789012
https://youtube.googleapis.com/embed/123456789012
https://www.youtube.com/embed/123456789012
http://www.youtube.com/embed/123456789012
//www.youtube.com/embed/123456789012
www.youtube.com/embed/123456789012
http://vimeo.com/25451551
http://player.vimeo.com/video/25451551
https://player.vimeo.com/video/6969232737373733383782383273287328327342873
http://player.vimeo.com/video/6969
http://plaser.vimeo.com/video/6969
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression