import Foundation
let pattern = #"((?<stat>\w+)(\s*([Dd][cC]|@)\s*(?<num>\d+))?|())\s*\]"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
[1 min: STR-Armor Rating](swept downstream to [room L]/able to reach edge)
[1min: STR DC 12](swept downstream to [room L]/able to reach edge)
[12 hr: STR DC 12](swept downstream to [room L]/able to reach edge)
How does one [WIS@15](fail info/pass info 1)
[ssdsd](sd/ds)
[ssdsd](-/ds)
[ssdsd](player is Incapacitated for 1d4 rounds/-)
[Con](sleep for 1d6x10 minutes/-)
[Dex](2d6 damage/half)
[CON](lose 1hp every minute/-)
[STR](-/upward thrust dislodges debris - critical: door opens)
[DEX](slide down to pit/-)
[level 2 - room T]
[CON-Armor Rating](1d8 damage/-)
[STR-Armor Rating](swept downstream to [room L]/able to reach edge)
[Dex](-/pull up bracelet with chain)
[paralyze](paralyzed 3d6 turns/-)
[wis](cannot understand/-)
[poison](unconscious 1d6 turns/-)
"""#
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