46 lines
1.4 KiB
Python
46 lines
1.4 KiB
Python
import re
|
|
|
|
|
|
def normalize_phone(phone: str) -> str | None:
|
|
"""
|
|
Приводит телефон к формату +7-xxx-xxx-xx-xx
|
|
Поддерживает:
|
|
- 89231234567 → +7-923-123-45-67
|
|
- +79231234567 → +7-923-123-45-67
|
|
- 8 (923) 123-45-67 → +7-923-123-45-67
|
|
- 79231234567 → +7-923-123-45-67
|
|
- 9231234567 → +7-923-123-45-67
|
|
"""
|
|
cleaned = re.sub(r'[^\d+]', '', phone.strip())
|
|
digits = re.sub(r'\D', '', cleaned)
|
|
|
|
if len(digits) == 10:
|
|
digits = '7' + digits
|
|
elif len(digits) == 11:
|
|
if digits.startswith('8'):
|
|
digits = '7' + digits[1:]
|
|
elif not digits.startswith('7'):
|
|
return None
|
|
else:
|
|
return None
|
|
|
|
if not (len(digits) == 11 and digits.startswith('7')):
|
|
return None
|
|
|
|
formatted = f"+7-{digits[1:4]}-{digits[4:7]}-{digits[7:9]}-{digits[9:11]}"
|
|
return formatted
|
|
|
|
|
|
def is_valid_phone(phone: str) -> bool:
|
|
normalized = normalize_phone(phone)
|
|
return normalized is not None
|
|
|
|
|
|
def extract_phone_from_text(text: str) -> str | None:
|
|
"""Пытается извлечь номер телефона из текста"""
|
|
# Ищем последовательность цифр длиной 10-12
|
|
phone_pattern = r'(\+?\d[\d\s\-\(\)]{7,}\d)'
|
|
match = re.search(phone_pattern, text)
|
|
if match:
|
|
return normalize_phone(match.group(1))
|
|
return None |