import Foundation
let pattern = #"(?:\d([\-\. ])?){7,15}"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
888-426-6840 215-861-6239
SPAIN Toll-Free: 900-8-01334
Caller Paid: 9-1-7878580
ITN Number: (*8) 2650 6840
Sandy Phillips 845-433-6476
USA Toll-Free: 888-426-6840
USA Caller Paid: 215-861-6239
Blackberry One Click +1-888-426-6840x6014774#
Call-In#: 888-426-6840 or 215-861-6239
USA/Mexico Toll-Free: 888-426-6840
Hungary Toll-Free: 06-800-19-306
Canada Toll-Free: 888-426-6840
UK Toll-Free: 0800-368-0638/02030596451
USA Toll-Free: 888-426-6840
USA Caller Paid: 215-861-6239
United Kingdom Caller Paid 0-20-30596451
United Kingdom Toll-Free 0800-368-0638
"""##
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