import Foundation
let pattern = #"^(?P<bucket>[^\/]+)\/(?:(?P<prefix>.+)\/)?AWSLogs\/(?P<aws_account_id>[\d]{12})\/elasticloadbalancing\/(?P<region>[\w\d\-]+)\/(?P<year>\d{4})\/(?P<month>\d{2})\/(?P<day>\d{2})\/(?P=aws_account_id)_elasticloadbalancing_(?P=region)_(?P<load_balancer_id>[\w\.\-\d]+)_(?P<end_time>\d{8}T\d{4}Z)_(?P<ip_address>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))_(?P<random_string>.+)\.log\.gz$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
log-bucket/AWSLogs/113901497002/elasticloadbalancing/us-east-1/2020/04/26/113901497002_elasticloadbalancing_us-east-1_app.us-east-lt-alb.5ac1c221b7cf2245_20200426T0225Z_34.233.232.149_nhinzchd.log.gz
log-bucket/web-lt/AWSLogs/113901497002/elasticloadbalancing/us-east-1/2020/04/26/113901497002_elasticloadbalancing_us-east-1_app.us-east-lt-alb.5ac1c221b7cf2245_20200426T0225Z_34.233.232.149_nhinzchd.log.gz
"""#
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