import Foundation
let pattern = #"(?P<PVS>pvs): (?P<src>[^:]+):(?P<src_port>\d{1,5})\|(?P<dest>[^:]+):(?P<dest_port>\d{1,5})\|(?P<protocol>\d{1,3})\|(?P<PVS_pluginid>\d{1,5})\|(?P<PVS_eventname>[^\|]+)\|(?P<PVS_data>[^\|]+)\|(?P<PVS_data2>[^\|]+)?\|(?P<PVS_risk>[^\|]+)([\r\n]+)"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
May 13 09:15:44 10.x.x.x pvs: 10.x.x.x:53|10.y.y.y:53|17|7024|DNS Client Queries|PVS has observed this host perform a DNS lookup. The most recent DNS query performed was for: |hostname.some.ORG to the server at 10.y.y.y|NONE
May 13 09:15:42 10.x.x.x pvs: 10.y.y.y32:61565|10.z.z.z:80|6|7041|HTTP request detection|The following GET/POST request was observed:|DIP: 10.z.z.z:80;URI: /department/Admin/ProjectManage/Lists/Develop%20New%20PM%20tracking/Research;Referer: None;Host: hostname2.some.org;Query: YES;PROTO: 1.0|NONE
May 13 09:15:42 10.x.x.x pvs: 10.y.y.y32:61566|10.z.z.z:80|6|7041|HTTP request detection|The following GET/POST request was observed:|DIP: 10.z.z.z:80;URI: /committee_name/committees/budget_perf/DeptITPlansFY201516ThroughFY201920/CON;Referer: None;Host: hostname2.some.org;Query: NO;PROTO: 1.0|NONE
"""#
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