Стоян обнови решението на 18.04.2014 22:47 (преди над 10 години)
+import re
+
+
+class Patterns:
+ hostname = \
+ r'(?P<hostname>(([a-zA-Z0-9][a-zA-Z0-9-]{,61}[a-zA-Z0-9]|[a-zA-Z0-9])\.)+' + \
+ r'(?P<domain_TLD>[a-zA-Z]{2,3}(\.[a-zA-Z]{2})?))\b'
+ email = r'(?P<username>\b[a-zA-Z0-9][\w\+\.-]{,200})@' + hostname
+ phone_number = r'(?P<country_code>\b0(?!0)|((\b00|\+)[1-9]\d{,2}))' + \
+ r'([- \(\)]{,2}\d){6,11}\b'
+ ip_address = r'([2][0-5][0-5]|[1][0-9]{2}|[1-9][0-9]|[0-9])\.' + \
+ r'([2][0-5][0-5]|[1][0-9]{2}|[1-9][0-9]|[0-9])\.' + \
+ r'([2][0-5][0-5]|[1][0-9]{2}|[1-9][0-9]|[0-9])\.' + \
+ r'([2][0-5][0-5]|[1][0-9]{2}|[1-9][0-9]|[0-9])'
+ number = r'-?((0(?!0)|[1-9][0-9]*)(\.[0-9]+)?)'
+ integer = r'-?(0(?!0)|[1-9][0-9]*)\b'
+ date = r'\b\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])'
+ time = r'(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9])'
+ datetime = date + r'[T ]' + time
+
+
+class PrivacyFilter:
+ def __init__(self, text):
+ self.preserve_phone_country_code = False
+ self.preserve_email_hostname = False
+ self.partially_preserve_email_username = False
+ self.text = text
+ self._email_pattern = re.compile(Patterns.email)
+ self._phone_pattern = re.compile(Patterns.phone_number)
+
+
+ def filtered(self):
+ def email_filter(match_object):
+ if self.partially_preserve_email_username:
+ if len(match_object.group('username')) >= 6:
+ return match_object.group('username')[0:3] + \
+ '[FILTERED]@' +\
+ match_object.group('hostname')
+ return '[FILTERED]@' + match_object.group('hostname')
+ if self.preserve_email_hostname:
+ return '[FILTERED]@' + match_object.group('hostname')
+ return '[EMAIL]'
+
+ def phone_filter(match_object):
+ if self.preserve_phone_country_code:
+ return match_object.group('country_code') + ' [FILTERED]'
+ return '[PHONE]'
+
+ filtered_email = re.sub(self._email_pattern, email_filter, self.text)
+ return re.sub(self._phone_pattern, phone_filter, filtered_email)
+
+
+class Validations:
+ @classmethod
+ def is_email(cls, value):
+ return bool(re.match(Patterns.email + '$', value))
+
+ @classmethod
+ def is_phone(cls, value):
+ return bool(re.match(Patterns.phone_number + '$', value))
+
+ @classmethod
+ def is_hostname(cls, value):
+ return bool(re.match(Patterns.hostname + '$', value))
+
+ @classmethod
+ def is_ip_address(cls, value):
+ return bool(re.match(Patterns.ip_address + '$', value))
+
+ @classmethod
+ def is_number(cls, value):
+ return bool(re.match(Patterns.number + '$', value))
+
+ @classmethod
+ def is_integer(cls, value):
+ return bool(re.match(Patterns.integer + '$', value))
+
+ @classmethod
+ def is_date(cls, value):
+ return bool(re.match(Patterns.date + '$', value))
+
+ @classmethod
+ def is_time(cls, value):
+ return bool(re.match(Patterns.time + '$', value))
+
+ @classmethod
+ def is_datetime(cls, value):
+ return bool(re.match(Patterns.datetime + '$', value))