9

Hey I would like to check if UITextView (maybe this could be relevant or not) contains phone number in text. I am using Swift 2.3, but if you got it in Swift 3 I will try to translate it.

Should work for these inputs for exemple:

  • "Good morning, 627137152"
  • "Good morning, +34627217154"
  • "Good morning, 627 11 71 54"

The last case it's easy if other works, just replace " " occurences to "" and check the previous function containsPhone.

I have tried this solution but doesn't works with the first case: (Find phone number in string - regular)

Thank you.

Community
  • 1
  • 1
Eironeia
  • 771
  • 8
  • 20

4 Answers4

15

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)
    }
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • How this will be in swift 2.3? I am not able to get it work. – Eironeia Jun 07 '17 at 07:56
  • 1
    I'm sorry I don't use Swift 2 anymore. Please lookup the method signatures in the documentation. I'd like to encourage you to update to Swift 3. (Swift 4 is upcoming). – vadian Jun 07 '17 at 08:04
2

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
}
Alex Shubin
  • 3,549
  • 1
  • 27
  • 32
1

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

Deb S
  • 509
  • 5
  • 16
1

Swift 5 Very Easy way with two line of Code this will help you only to get a decimal number from string

//MARK:- if the Single Phone number in String 
var tempphone = "+34627217154 \n Good morning"
tempphone = tempphone.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")

print(tempohone) 
//MARK:- Result No: 34627217154


//MARK:- if the Multiple Phone number in String 
var tempphone = "Good morning, 627137152 \n Good morning, +34627217154 \n Good morning, 627 11 71 54"
tempphone = tempphone.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")

print(tempohone) 
//MARK:- Result No:  62713715234627217154627117154
Shakeel Ahmed
  • 5,361
  • 1
  • 43
  • 34