import Foundation
let pattern = #"(?P<event_message>A user account was unlocked\.)\s+Subject:\s+Security ID:\s+(?P<subject_security_id>.*?)\s+Account Name:\s+(?P<subject_account_name>.*?)\s+Account Domain:\s+(?P<subject_account_domain>.*?)\s+Logon ID:\s+(?P<subject_logon_id>.*?)\s+Target Account:\s+Security ID:(?P<target_security_id>.*?)\s+Account Name:\s+(?P<target_account_name>.*?)\s+Account Domain:\s+(?P<target_account_domain>.*)"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"A user account was unlocked. Subject: Security ID: S-1-5-21-173871781-544419543-443003237-500 Account Name: Administrator Account Domain: AV Logon ID: 0x1E3AD Target Account: Security ID: S-1-5-21-173871781-544419543-443003237-1111 Account Name: test Account Domain: AV"#
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