import Foundation
let pattern = #"([\d]*)(.|,)[\d](e|E)[\d]+"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
Valid floating points:
1
+1
-1
65
+65
-65
5.2
5,2
5.225
5,225
985.225
985,225
985.
,225
+5.2
+5,2
+5.225
+5,225
+985.225
+985,225
+985.
+,225
-5.2
-5,2
-5.225
-5,225
-985.225
-985,225
-985.
-,225
5.2E3
5.2e3
+5.2e3
-5.2e3
5,2E3
5,2e3
-5,2e3
+5,2e3
5.2e112
+5.2e112245
-5.2e99999
5,2e112
-5,2e112245
+5,2e99999
5.2e+3
+5.2e+3
-5.2e+3
5,2e-3
-5,2e-3
+5,2e-3
5.e3
5.e+3
+5.e+3
-5.e+3
5,e-3
-5,e-3
+5,e-3
,225e123
+,225e123
-,225e123
.225e123
+.225e123
-.225e123
Not floating points
,
,
,
.
.
.
.e
,e
.e2
,e2
,225e
+,225e
-,225e
.225e
+.225e
-.225e
"""#
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