import Foundation
let pattern = #"^(\(?([\d \-\)\–\+\/\(.]+){5}\)?([ .\-–\/]?)([\d]+))$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
US (North American) Phone Numbers
1-800-123-4567
(123)456-7890
1234567890
123-456-7890
123.456.7890
123 456 7890
(123) 456 7890
UK Phone Numbers
+447222555555
+44 7222 555 555
(0722) 5555555 #2222
French Phone Numbers
0123456789
01 23 45 67 89
01.23.45.67.89
0123 45.67.89
0033 123-456-789
+33-1.23.45.67.89
+33 – 123 456 789
+33(0) 123 456 789
+33 (0)123 45 67 89
+33 (0)1 2345-6789
+33(0) – 123456789
German Phone Numbers
(06442) 3933023
(02852) 5996-0
(042) 1818 87 9919
06442 / 3893023
06442 / 38 93 02 3
06442/3839023
042/ 88 17 890 0
+49 221 549144 – 79
+49 221 – 542194 79
+49 (221) – 542944 79
0 52 22 – 9 50 93 10
+49(0)121-79536 – 77
+49(0)2221-39938-113
+49 (0) 1739 906-44
+49 (173) 1799 806-44
0214154914479
02141 54 91 44 79
01517953677
+491517953677
015777953677
02162 – 54 91 44 79
(02162) 54 91 44 79
Chinese Phone Numbers
0936-4211235
89076543
010-12345678-1234
Chinese Mobile Phone Numbers
008618311006933
+8617888829981
1911925564
India Phone Numbers
03595-259506
03592 245902
03598245785
9775876662
0 9754845789
0-9778545896
+91 9456211568
91 9857842356
919578965389
Brazilian Phone Numbers
(12) 123 1234
(01512) 123 1234
(0xx12) 1234 1234
Australian Phone Numbers
0732105432
1300333444
131313
Dutch Phone Numbers
+31235256677
+31(0)235256677
023-5256677
Sweden Phone Numbers
+46 8 123 456 78
08-123 456 78
0123-456 78
thx to https://regexpattern.com/phone-number/
"""##
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