Reputation: 337
I'm trying to validate a phone number using Regex, using the below syntax. The number must start with 9 and has 9 digits after that. Can you please advice what can probably be wrong in this code.
import re
phn = "9123456789"
res = re.findall("(9)?[0-9]{9}", phn)
print (res)
O/p:
['9']
Upvotes: 1
Views: 1123
Reputation: 113
It is possible to use python library phonenumbers to validate the phone number extracted by commonregex :
import import commonregex
import phonenumbers
phone_list = commonregex.phone.findall(input_string)
for phone in phone_list:
phonenumbers.is_valid_number(phonenumbers.parse(phone, None))
I hope it helps you.
Upvotes: 0
Reputation: 508
Here is a very good webside you might love: it makes regex easy.
Here is an extract of the website with the solution of you problem 9[0-9]{9}
:
Upvotes: 0
Reputation: 57095
?
means "optionally." If your number must start with 9, you do not need ?
:
re.findall("9[0-9]{9}", phn)
Or, better:
re.findall(r"9\d{9}", phn)
Upvotes: 2