import Foundation
let pattern = #"^(?<date>\d{4}\-\d{2}\-\d{2})\s+(?<time>\d{2}\:\d{2}\:\d{2})\s+(?<sip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(?<csmethod>GET|POST|PUT|PATCH|DELETE)\s+(?<csuristem>.+?)\s+(?<csuriquery>.+?)\s+(?<sport>\d{1,3})\s+(.+?)\s+(?<cip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(?<csUseragent>.+?)\s+(?<scstatus>\d{1,3})\s+(?<scsubstatus>\d{1,3})\s+(?<scwin32status>\d+)\s+(?<scbytes>\d+)\s+(?<csbytes>\d+)\s+(?<timetaken>\d+)?$"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"2014-05-06 10:27:17 10.200.40.56 GET / - 443 - 10.200.28.7 Mozilla/5.0+(compatible;+MSIE+9.0;+Windows+NT+6.1;+WOW64;+Trident/5.0) 401 2 2148074254 1880 428 109"#
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