import Foundation
let pattern = #"^\s*(\w+)(?:\s+(V[0-9A-F]|0x[0-9A-F]+|[0-9]+|I|DELAY|SOUND))?(?:,\s+(V[0-9A-F]|0x[0-9A-F]+|[0-9]+|DELAY))?(?:,\s+([0-9]+|0x[0-9A-F]))?\s*$"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive])
let testString = #"""
NOP
CLEAR
RETURN
JUMP 0x123
CALL 0x123
IFEQ V3, 42
IFNE V5, 0x4A
IFEQ V2, V4
SET VE, 42
ADD V7, 56
SET V4, V6
OR V9, V0
AND V4, V6
XOR V2, V9
ADD VF, VD
DEC V8, V3
RSH V6
SUB V3, V8
LSH VB
IFNE V8, V9
SET I, 0x200
JMPO 0x230
RAND V0, 68
DRAW V2, V3, 0xF
IFKEY V9
IFNKEY V8
SET V8, DELAY
WAIT V7
SET DELAY, VA
SET SOUND, VB
ADD I, V0
SPRITE VD
BCD 7
DUMP VF
LOAD V3
"""#
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