import Foundation
let pattern = ##"""
#
# Inspired by http://stackoverflow.com/questions/6556559/youtube-api-extract-video-id
# Example: https://www.youtube.com/watch?v=o8QuLYXKNCg&rel=0&autoplay=1
#
# Match any youtube URL
(?:https?://)? # Optional scheme. Either http or https
(?:www\.)? # Optional www subdomain
(?: # Group host alternatives
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com
(?: # Group path alternatives
/embed/ # Either /embed/
| /v/ # or /v/
| /watch\?v= # or /watch\?v=
) # End path alternatives.
)? # End host alternatives.
([\w-]{10,12}) # Allow 10-12 for 11 char youtube id.
(?:[&?](.*)) # Optional Parameters
$
"""##
let regex = try! NSRegularExpression(pattern: pattern, options: .allowCommentsAndWhitespace)
let testString = #"https://www.youtube.com/watch?v=o8QuLYXKNCg&rel=0&autoplay=1&autoplay=2&autoplay=3&autoplay=4"#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
if let firstMatch = regex.firstMatch(in: testString, range: stringRange) {
let result: [String] = (1 ..< firstMatch.numberOfRanges).map { (testString as NSString).substring(with: firstMatch.range(at: $0)) }
print(result)
} else {
print("No matches were found.")
}
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