Check if exists phone number in String

NSDataDetector provides a convenient way to do that:

let string = "Good morning, 627137152 \n Good morning, +34627217154 \n Good morning, 627 11 71 54"

do {
   let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)
   let numberOfMatches = detector.numberOfMatches(in: string, range: NSRange(string.startIndex..., in: string))
   print(numberOfMatches) // 3
} catch {
   print(error)
}

or if you want to extract the numbers

let matches = detector.matches(in: string, range: NSRange(string.startIndex..., in: string))

for match in matches{
    if match.resultType == .phoneNumber, let number = match.phoneNumber {
        print(number)
    }
}

You can check phone no with this regex -

1?\W*([2-9][0-8][0-9])\W*([2-9][0-9]{2})\W*([0-9]{4})(\se?x?t?(\d*))?

To find match (I am using current project)

func matches(for regex: String, in text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex)
        let nsString = text as NSString
        let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
        print("\(results)")
        return results.map { nsString.substring(with: $0.range)}
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

Here is the test result - enter image description here


This func takes your string and returns array of detected phones. It's using NSDataDetector, if this mechanism won't fit your needs in the end, you'll be probably need to build your own algorithm:

func getPhoneNumber(from str: String) -> [String] {
    let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)
    let matches = detector.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))

    var resultsArray = [String]()

    for match in matches {
        if match.resultType == .phoneNumber,
            let component = match.phoneNumber {
            resultsArray.append(component)
        }
    }
    return resultsArray
}