phone.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import re


class Phone:
    INVALID_NUMBER = ['000', '000', '0000']

    NON_DIGIT = re.compile(r'[^\d]+')
    PARTS = re.compile(r'^1?(\d{3})(\d{3})(\d{4})$')

    def __init__(self, number):
        self._parts = self._parse_number(number)

    @property
    def number(self):
        return ''.join(self._parts)

    def area_code(self):
        return self._parts[0]

    def pretty(self):
        return "(%s) %s-%s" % self._parts

    @classmethod
    def _parse_number(cls, number):
        number = cls.NON_DIGIT.sub('', number)
        m = cls.PARTS.match(number)
        return m.groups() if m else cls.INVALID_NUMBER

Comments

Just tidied up regex names and moved them into the class

helenst commented 30 May 2016 at 20:06 UTC

You're not logged in right now. Please login via GitHub to comment