import Foundation
let pattern = #"(?=.*Critical)(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2}):(?P<milsec>\d{3}) (\[Loot] Gained (?P<xp>\S+) XP?|\[Loot] Item Acquired: (?P<loot>.*)|\[Loot] Gained (?P<dram>\S+) Dram?|\[Loot] Earned (?P<reputation>\S+) Reputation?|\[Combat] (?P<dude_hurt>.+) took (?P<damages>\S+) damage from (?P<damage_dealer>[\S]+))"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
19:59:16:394 [Combat] player1 took 4301 damage from Stafrusher(47)
19:59:16:547 [Combat] Stafrage(45) took 12049 damage from player2
19:59:17:060 [Combat] Stafrage(45) took 8621 damage from player3 (Critical)
19:59:17:375 [Combat] Stafrage(45) took 7931 damage from player2 (Critical)
"""#
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