import Foundation
let pattern = #"^(?=(?:[^\n\d]*\d){5})(?!(?:[^\n\d]*\d){21})(?:\(\+\d+\)|\+\d+) ?\d+(?:-\d+)*$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
(+355)250235
+91 123456789012
(+355) 250-236-236-789
(+355) 2502-3656-1236-8789
+920123456789012345987
(+355)2
+91
(+355) 2
+920123456789012345987
"""#
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