import Foundation
let pattern = #"^(([1-9]\d{0,2}((,\d{3})*|(\d{3})*))|0?)(\.\d+)?$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
Capture the following numbers
1
0
1223
332243243423243243243423423243
12
1000000000
111,000,000
1000.000398
1,123,333.2222222
1.22222222
1,234,345,673,345,345,345.123455
1222222222
0.123345
.1234
012,312
.12332
1000.122.122
1,231,423,434.3746472773640000000000
Don't Capture:
2000..0000
,111.45
start of line
#first is 1 - 3 digits
# can't start with zero
# unless the zero is followed by a period
#then optional (optional comma then 3 digits)
#then optional (period then unlimited digits)
end of line
"""##
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