How to detect URLs, Addresses, Phone Numbers and Dates using NSDataDetector

Using NSDataDetector class we can detect URLs, addresses, phone numbers and dates inside any string.
Using below code snippet you can detect these and also find their range respectively.

let string = "This is an address PO Box 7775, San Francisco, CA. This is a url http:/ This is second url: This is mobile number
+18987656789. This is a date 01/26/2019"

let detectorType: NSTextCheckingResult.CheckingType = [.address, .phoneNumber, .link, .date]
do {
    let detector = try NSDataDetector(types: detectorType.rawValue)
    let results = detector.matches(in: string, options: [], range: NSRange(location: 0, length:
    for result in results {
        if let range = Range(result.range, in: string) {
            let matchResult = string[range]
            print("result: \(matchResult), range: \(result.range)")
} catch {
    print("handle error")
The console log is below of above code:
result: PO Box 7775, San Francisco, CA., range: {19, 31}
result:, range: {65, 30}
result:, range: {117, 23}
result: +18987656789, range: {164, 12}

Leave a Reply

Your email address will not be published. Required fields are marked *