Hi I want to do a regular expression of Phone validation. It must match with Android Phone matcher class. So, I tried the following expression but it is not working in one scenario.
Expression: (\+[0-9]+[\- \.])?(\([0-9]+\)[\- \.])?([0-9][0-9\- \.]+[0-9])
It is not working for following number
123d453
But it is working fine in https://regexr.com/ By using (+[0-9]+[- .])?(([0-9]+)[- .])?([0-9][0-9- .]+[0-9])
Please help me.
Code
let phone = "123d4"
let phonereg = "(\\+[0-9]+[\\- \\.]*)?(\\([0-9]+\\)[\\- \\.]*)?([0-9][0-9\\- \\.]+[0-9])"
if phone.range(of: phonereg, options: .regularExpression, range: nil, locale: nil) != nil{
print("valid phone")
}
else{
print("Invalid phone")
}
ANSWER: Here are the solutions for above issue.
let phone = "123d4"
let phonereg = "(\\+[0-9]+[\\- \\.]*)?(\\([0-9]+\\)[\\- \\.]*)?([0-9][0-9\\- \\.]+[0-9])"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", phonereg)
let result = phoneTest.evaluate(with: phone)
if result{
print("valid phone")
}
else{
print("Invalid phone")
}