formatting phone numbers to a single view

50 views Asked by At

How do I format a phone number so that when I receive a number during user registration, formatting occurs immediately?

I need that after registering a user, his phone number (and he can enter it as 8990000000 and 79000000000 or so +79800000000 and so on) is converted in this format tel: +7-900-821-88-99

I tried to do it like

def formatting_number(phone): NUM_RE = re.compile((r".*(\d).*(\d).*(\d).*(\d).*(\d).*(\d).*(\d).*(\d).*(\d).*(\d).*")) phone['Tel'] = phone['Tel'].apply(lambda x: "tel:" + "+7" ''.join(NUM_RE.match(x).groups()))

but i think it won't work

All what i do it's for FastAPI project

1

There are 1 answers

0
Andrej Kesely On

I'd do custom logic in several steps, for example collect all digits, check if there is 7 at the beginning etc.:

import re

testcases = ["8990000000", "79000000000", "+79800000000"]

for t in testcases:
    digits = "".join(re.findall(r"\d+", t))

    if len(digits) == 11 and digits[0] == "7":
        digits = digits[1:]

    final_format = re.sub(
        r"(\d{3})(\d{3})(\d{2})(\d{2,})", r"+7-\g<1>-\g<2>-\g<3>-\g<4>", digits
    )

    print(f"{t:<15} {final_format:>15}")

Prints:

8990000000      +7-899-000-00-00
79000000000     +7-900-000-00-00
+79800000000    +7-980-000-00-00