Ashish Bainade Ashish Bainade - 3 months ago 9
Python Question

regular expression to match phone number but not zipcodes

I have written below regex

phone_regex = re.compile(r'(\+?\(?\+?\d{1,}\)?[-\s\.]?\d{1,}[-\s\.]?\d{1,}[-\s\.]?\d{1,}[-\s\.]?\d{1,}[-s\.]?)')


It matches & identifies phone numbers along with country codes eg
+91 9561217616
,
(+91) 9561 217 616
,
+(91) 9561217616
,
+91-9833775049

but it also match
431003
(zipcode) can someone help out to write regex to match only phones but not zipcodes

Answer

(?:\+\d\d|\(\+\d\d\)|\+\(\d\d\))(?:\s+|-)\d{4}(?:\s+|-)?\d{3}(?:\s+|-)?\d{3}$

  • (?:\+\d\d|\(\+\d\d\)|\+\(\d\d\)) +00 or (+00) or +(00)
  • (?:\s+|-) a gap (at least one space or a single dash)
  • \d{4} 4 numbers (0000)
  • (?:\s+|-)? an optional gap (at least one space or a single dash or -nothing at all)
  • \d{3} 3 numbers (000)
  • (?:\s+|-)? an optional gap
  • \d{3} 3 numbers (000)

As a zip code won't fulfill all these requirements, it won't pass the regex.