Божидар обнови решението на 22.04.2014 15:06 (преди над 10 години)
+import re
+
+
+class PrivacyFilter:
+ def __init__(self, text):
+ self.__text = text
+ self.preserve_phone_country_code = False
+ self.preserve_email_hostname = False
+ self.partially_preserve_email_username = False
+
+ def filtered(self):
+ result = ""
+
+ def email_replacer(match):
+ if len(match.group()) - len(match.group("tail")) < 6:
+ return "[FILTERED]" + match.group("tail")
+ else:
+ return match.group()[:3] + "[FILTERED]" + match.group("tail")
+ if self.partially_preserve_email_username:
+ result = re.sub(self._email, email_replacer, self.__text)
+ elif self.preserve_email_hostname:
+ result = re.sub(self._email, "[FILTERED]\g<tail>", self.__text)
+ else:
+ result = re.sub(self._email, "[EMAIL]", self.__text)
+
+ def phone_replacer(match):
+ if (self.preserve_phone_country_code and
+ re.match(self._inter_phone_prefix, match.group("prefix"))):
+ return match.group("prefix") + " [FILTERED]"
+ else:
+ return "[PHONE]"
+ result = re.sub(self._phone, phone_replacer, result)
+ return result
+
+ _domain_name = r"[\da-zA-Z][\da-zA-Z-]{,62}[\da-zA-Z]"
+ _TLD = r"[a-zA-Z]{2,3}(\.[a-zA-Z]{2,3})?"
+ _hostname = "(?:" + _domain_name + r"\.)+" + _TLD
+ _email = r"\b[a-zA-Z\d][\w+.-]{,200}(?P<tail>@" + _hostname + r")\b"
+ _local_phone_prefix = r"(?<![0-9a-zA-Z+])0(?!0)"
+ _inter_phone_prefix = r"(?:\b00|\+)[1-9]\d{,2}"
+ _phone_body = r"([ \(\)-]{0,2}\d){6,11}\b"
+ _phone = r"(?P<prefix>" + _local_phone_prefix +\
+ "|" + _inter_phone_prefix + ")" + _phone_body
+ _byte = r"(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])"
+ _ip = r"\b(?:" + _byte + r"\.){3}" + _byte
+
+ _integer = r"-?(?:0|[1-9][0-9]*)"
+ _number = _integer + r"(?:\.[0-9]+)?"
+
+ _date = r"[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])"
+ _time = r"(?:0\d|1\d|2[0-3]):(?:0\d|[1-5]\d):(?:0\d|[1-5]\d)"
+ _datetime = _date + "( |T)" + _time
+
+
+class Validations:
+ @classmethod
+ def is_email(cls, text):
+ return re.match(PrivacyFilter._email + "$", text) is not None
+
+ @classmethod
+ def is_phone(cls, text):
+ return re.match(PrivacyFilter._phone + "$", text) is not None
+
+ @classmethod
+ def is_hostname(cls, text):
+ return re.match(PrivacyFilter._hostname + "$", text) is not None
+
+ @classmethod
+ def is_ip_address(cls, text):
+ return re.match(PrivacyFilter._ip + "$", text) is not None
+
+ @classmethod
+ def is_number(cls, text):
+ return re.match(PrivacyFilter._number + "$", text) is not None
+
+ @classmethod
+ def is_integer(cls, text):
+ return re.match(PrivacyFilter._integer + "$", text) is not None
+
+ @classmethod
+ def is_date(cls, text):
+ return re.match(PrivacyFilter._date + "$", text) is not None
+
+ @classmethod
+ def is_time(cls, text):
+ return re.match(PrivacyFilter._time + "$", text) is not None
+
+ @classmethod
+ def is_datetime(cls, text):
+ return re.match(PrivacyFilter._datetime + "$", text) is not None