Skip to content

Instantly share code, notes, and snippets.

@nskeip
Created March 17, 2012 18:00
Show Gist options
  • Save nskeip/2063600 to your computer and use it in GitHub Desktop.
Save nskeip/2063600 to your computer and use it in GitHub Desktop.
Helps to recognize a celular phone number in a string with non-celular numbers.
#-*- coding: UTF-8 -*-
import re
def recognize_phone(s):
"""
>>> f = recognize_phone
>>> f(u'8-912-234-56-78')
u'8-912-234-56-78'
>>> f(u'8-912-234-56-78 факс:8-343-234-56-78')
u'8-912-234-56-78'
>>> f(u'тел. 8-912-234-56-78 8-343-234-56-78')
u'8-912-234-56-78'
>>> f(u'8-343-234-56-78 8-912-234-56-78')
u'8-912-234-56-78'
>>> f(u' тел. 8-343-234-56-78 тел. 8-912-234-56-78 ')
u'8-912-234-56-78'
>>> f(u'(29)36-41-34; 8-912-234-56-78')
u'8-912-234-56-78'
>>> f(u'8/912/234-56-78')
u'8/912/234-56-78'
"""
m = re.search(r'\b(\+?[87][/\-]9[0-9/\-]+)', s)
if m:
return m.group(0)
@qnub
Copy link

qnub commented Mar 18, 2012

For other side - in my project i force user to input phone number as solid number string w/o spaces, minus or other marks and then parce rhem from end (in case if number not in international format)

def phone(num):
    """
    Phone formatter.
    """
    num = re.sub('\D', '', num)

    return '+%s (%s) %s-%s-%s' % (
        num[:-10],
        num[-10:-7],
        num[-7:-4],
        num[-4:-2],
        num[-2:]
    )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment