import Foundation
let pattern = #"(?:account:(.+))(?:site:(.+))(?:zone:(.+))-->|(?:site:(.+))(?:zone:(.+))(?:size:(.+))\s+-->|(?:placement:(.+))-->"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive])
let testString = #"""
<!-- Account: QA 1 Test Site: Video Test Site for Mobile Team (Nitin) Zone: ROS -->
http://optimized-by.rubiconproject.com/a/api/vast.xml?account_id=2763&site_id=40876&zone_id=170462
<!-- Begin Rubicon Project Tag -->
<!-- Site: DOM_TOLIVER_MWEB Zone: Interstitials Size: Mobile Interstitial Landscape -->
<!-- PLACEMENT: Homepage; Above the Fold -->
<script language="JavaScript" type="text/javascript">
rp_account = '8092';
rp_site = '55880';
rp_zonesize = '340088-101';
rp_adtype = 'js';
rp_smartfile = '[SMART FILE URL]';
</script>
<script type="text/javascript" src="http://ads.rubiconproject.com/ad/8092.js"></script>
<!-- End Rubicon Project Tag -->
"""#
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