import Foundation
let pattern = #"^(?=-.*D$|\d.*C$)-?(?=(?:\d,?){1,13}\.)(?:0|[1-9]\d{0,2}(?:,\d{3})*)\.\d{2} [DC]$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
-0.48 D
-1.00 D
-2,000.00 D
-100,000.56 D
-100,000.00 D
-1,123,456.43 D
-1,123,456,000,000.43 D
-10,123,456,000,000.43 D
-1,123,456.43 C
-3,000,62.45 D
-03,000.45 D
-.23 D
0.23 C
1.00 C
2,000.00 C
100,000.56 C
100,000.00 C
1,123,456.43 C
1,123,456,000,000.43 C
10,123,456,000,000.43 C
"""#
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