import Foundation
let pattern = #".+HappyMK\s?(?<action>\S+)\s(?<chain>\w+):\sin:(?<int_in>\S+)\sout:(?<int_out>\S+), src-mac\s(?<src_mac>\S+),\sproto\s(?<prot>\w+)(\s(?<flags>\S+),|,)\s(?<src_ip>\b(?:\d{1,3}\.){3}\d{1,3}\b):(?<src_port>\d+)->(?<dest_ip>\b(?:\d{1,3}\.){3}\d{1,3}\b):(?<dest_port>\d+),(\s(?<NAT>\w+)\s\((?<src_nat_localip>\b(?:\d{1,3}\.){3}\d{1,3}\b):(?<src_nat_local_port>\d+)->(?<src_nat_public_ip>\b(?:\d{1,3}\.){3}\d{1,3}\b):(?<src_nat_public_port>\d+)\)->(?<dest_nat_ip>\b(?:\d{1,3}\.){3}\d{1,3}\b):(?<dest_nat_port>\d+),)?(\sprio\s(?<prio>\d+->\d+),)?\slen\s(?<len>\d+)"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
May 30 11:56:03 10.10.0.1 May 30 11:56:04 HappyMK Accept forward: in:bridge-vlan11 out:ether1-gateway, src-mac 60:c5:47:09:bd:c8, proto TCP (SYN), 10.11.0.251:58615->17.134.126.209:443, prio 1->0, len 64
May 30 11:55:29 10.10.0.1 May 30 11:55:29 HappyMK Accept forward: in:vlan10 out:ether1-gateway, src-mac 00:60:6e:a5:61:c1, proto UDP, 10.10.0.14:62164->157.56.106.184:3544, NAT (10.10.0.14:62164->89.141.65.84:62164)->157.56.106.184:3544, len 84
May 30 11:56:25 10.10.0.1 May 30 11:56:26 HappyMK Accept forward: in:vlan10 out:ether1-gateway, src-mac 00:60:6e:a5:61:c1, proto UDP, 10.10.0.14:62164->157.56.106.189:3544, len 84
"""#
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