import Foundation
let pattern = #"^\[\S+\s+\S+\s+\S+\s+\S+\s+\S+\] \[(\w*:)?error\] (\[pid \d+(:tid \d+)?\] )?\[client (\S+)\] (\w+: )?ModSecurity:(( \[[^]]+\])*)? Access denied"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"[Sun Nov 08 14:58:57 2015] [error] [client 52.23.156.32] ModSecurity: [file "/etc/httpd/modsecurity.d/99_asl_zzzz_threat_intelligence.conf"] [line "73"] [id "355506"] [rev "1"] [msg "Atomicorp.com WAF Rules: Threat Intelligence Match for Known multi event attacker Source on Atomicorp Threat Intelligence RBL. See this URL for details http://www.atomicrbl.com/lookup"] [severity "ALERT"] Access denied with code 403 (phase 2). RBL lookup of 32.156.23.52.threat5.atomicrbl.com. succeeded at REMOTE_ADDR. [hostname "www.ourdomain.org"] [uri "/robots.txt"] [unique_id "Vj@3kaLy1rMAAAnKrs8AAAAY"]"#
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