Shaurya Sheth
Shaurya Sheth

Reputation: 185

Find a valid phone number using regular expression in python

phn1='412-1114-1234'

if re.search("\d{3}-\d{3}-\d{4}",phn1):
  print('It is a phone number')

else:
  print('It is not a phone number')

Output: It is not a phone number

But, when I pass the input:

phn1='4123-111-1234'

Output: It is a phone number

What is wrong in the code that I get a wrong output in the second phone number?

Upvotes: 1

Views: 97

Answers (2)

Deniz Kaplan
Deniz Kaplan

Reputation: 1609

It is the search method behaviour, try match instead. When you try to search, it finds a match from 123-111-1234 this part. For more information: search vs match

Upvotes: 0

user125661
user125661

Reputation: 1568

It matches 123-111-1234 (Everything except the first digit). Change your regex to: ^\d{3}-\d{3}-\d{4}$ to make sure it only matches the whole input (example).

Upvotes: 3

Related Questions