I'm developing an app which works with phone numbers, but I'm having a problem using regex to find the phonenumber in a string.
My app looks through the contact's phone number which can be:
(with dash "-")
XXXX-XXXX
XXXXX-XXXXX
(YY) XXXX-XXXX
(YY) XXXXX-XXXX
+ZZ (YY) XXXX-XXXX
+ZZ (YY) XXXXX-XXXX
(without dash)
XXXXXXXX
XXXXXXXXX
(YY) XXXXXXXX
(YY) XXXXXXXXX
+ZZ (YY) XXXXXXXX
+ZZ (YY) XXXXXXXXX
Based on all this possibilities above, I've written the following code:
let range = telefone.rangeOfString("[0-9]{4,5}-[0-9]{4}", options:.RegularExpressionSearch)
let range2 = telefone.rangeOfString("[0-9]{9}$", options:.RegularExpressionSearch)
var found: String?
if range != nil{
found = telefone.substringWithRange(range!)
}else if range2 != nil{
found = telefone.substringWithRange(range2!)
}
print(found)
range
is the regex to find phoneNumbers (with dash "-")
range2
is the regex to fund phone numbers (without dash)
With this code I get only the phone number, without the country code or the area code.
The problem is, this code returns nil on found variable when I test with a phone number like
+ZZ (YY) XXXXX-XXXX
Can someone help me find another way to write a regex to get only the "X" values of the string containing all the contact phone number?
UPDATE:
I noticed the code above, the variable range, returns null
var telefone = "+42 43 23123-2221"
let range = telefone.rangeOfString("\\d{4,5}\\-?\\d{4}", options:.RegularExpressionSearch)
print("range \(range)") //here returns nil