import Foundation
let pattern = #"((8|\+7?)[\- ]?)?(\(?\d{3}\)?[\- ]?)?([\d\- ]{7,10})"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = ##"""
======== local phone
765-43-21
7654321
765-4321
======== operator phone
(921) 765-43-21
(921) 7654321
(921) 765-4321
(921)765-43-21
(921)7654321
(921)765-4321
921765-43-21
9217654321
921765-4321
921-765-43-21
921-7654321
921-765-4321
======== world phone
+7 (921) 765-43-21
+7(921) 765-43-21
+7-(921) 765-43-21
7 (921) 765-43-21
7(921) 765-43-21
8 (921) 765-43-21
8(921) 765-43-21
8-(921) 765-43-21
8 (921) 765-43-21
8(921) 765-43-21
8-(921) 765-43-21
+7 9217654321
+79217654321
+7-9217654321
7 9217654321
79217654321
7-9217654321
8 9217654321
89217654321
8-9217654321
8 9217654321
89217654321
8-9217654321
======== not found
>>>>>>>>> 1. Коржев Артём Борисович 8-921-641-82-15;
======== bad
0 0 0 0
333 000
1 1 1205 1320 321
======== разбор
# world phone
(
(8|\+?7)
[\- ]?
)?
# operator phone
(
\(?
\d{3}
\)?
[\- ]?
)?
# local phone
[\d\- ]{7,10}
"""##
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