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:
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.
Validate Phone Number using Regular Expression We use String. matches() method and pass regular expression as argument. String. matches() returns the boolean value true if this string matches with the regular expression, else it returns false.
North American phone numbers To format phone numbers in the US, Canada, and other NANP (North American Numbering Plan) countries, enclose the area code in parentheses followed by a nonbreaking space, and then hyphenate the three-digit exchange code with the four-digit number.
A telephone number serves as an address for switching telephone calls using a system of destination code routing. Telephone numbers are entered or dialed by a calling party on the originating telephone set, which transmits the sequence of digits in the process of signaling to a telephone exchange.
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)
}
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With