import Foundation
let pattern = #"^(0{0,2}\+?389[\s./-]?)(\(?[0]?[7-7][0-9]\)?[\s./-]?)([2-9]\d{2}[\s./-]?\d{3})$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
+389 70 123 456
389-71-234-567
389-071-234-567
389-0071-234-567
00389.72.345.678
+389/73/456/789
389 75 123456
389 76-234-567
+38970123456
38971234567
0038972345678
+38973456789
38975123456
38976234567
38980123456
+38982123456
+389 70 123-456
+389 70 323-456
389(71)234.567
389(071)234.567
00389/723-456-78
+389 (73) 456.789
389 75 123/456
389 76-234.567
389.80.123.456
389.(080).123.456
+389-82-123-456
00389 (81) 234-56
389/931-234-56
+3899512-3456
00389(95)12.345
389/10-123-456
389 11-123/456
+389 12.123-456
"""#
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