import Foundation
let pattern = #"^(\d*([.,](?=\d{3}))?\d+)+((?!\2)[.,]\d\d)?$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
wrong
1,234,56
1.234.56
-1993
918,27.63
122.42.24
1,89,2
intl. format & US national format
2.56
14.56
134.56
1,234.56
2,991,234.00
Italian national format with 2 decimals
9,56
24,56
134,56
721.234,56
21.234,56
1.234,56
9.321.234,56
69.321.234,56
269.321.234,56
1.269.321.234,56
international format for the de_DE locale
1,56
14,56
134,56
1234,56
98281234,56
no cents
1
14
134
1,234
2,991,234
9
24
134
1.234
9.321.234
1
14
134
1234
98281234
"""#
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