import Foundation
let pattern = #"http(?:s)?:\/\/(?:www\.)?youtube\.com\/.*?watch%3Fv%([\d\w-_]+)"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
http://youtube.com/attribution_link?a=r_FgjB-RKNo&u=/watch%3Fv%3DB0_X8zWJd0Q%26feature%3Dem-uploademail
http://youtube.com/attribution_link?a=1crTn2Lx38I&u=/watch%3Fv%3DHhebhh2s5d4%26feature%3Dem-uploademail
http://youtube.com/attribution_link?a=_zMgiznzBto&u=/watch%3Fv%3D-kaoCPvUHJM%26feature%3Dem-uploademail
http://youtube.com/attribution_link?a=F8VReY1sT0A&u=/watch%3Fv%3D5RLM9rk0Q8s%26feature%3Dem-uploademail
https://www.youtube.com/watch?feature=player_detailpage&v=2eGUP16P_p4
"""#
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