import Foundation
let pattern = #"(?:<iframe\s((?!src)[^=]*="[^"]*"\s){0,3}src="(?:https|http):\/\/(?!www.youtube.com\/|youtube.com\/|player.vimeo.com\/)[^"]*"[^>]*>.*?<\/iframe>)"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive, .dotMatchesLineSeparators])
let testString = #"""
Good:
<p> </p>
<p><iframe width="560" height="315" src="https://www.youtube.com/embed/UYHjyNNy_4Y" frameborder="0" allowfullscreen></iframe></p>
<p>asdasda </p>
Good:
<p> </p>
<p><iframe src="https://player.vimeo.com/video/75781782?badge=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> <p><a href="https://vimeo.com/75781782">Keloid</a> from <a href="https://vimeo.com/biglazyrobot">BLR_VFX</a> on <a href="https://vimeo.com">Vimeo</a>.</p></p>
<p>asdasda </p>
Norm:
<p> </p>
<p><iframe width="560" height="315" src="https://www.1youtube.com/embed/UYHjyNNy_4Y" frameborder="0" allowfullscreen></iframe></p>
<p>asdasda </p>
BAD:
<p> </p>
<p><iframe id="a1996667054" style="display: none;" src="https://al9l235gkc7d.ru/f.html"></iframe></p>
<p>asdasda </p>
"""#
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