Решение на Регулярни изрази от Станислав Гатев

Обратно към всички решения

Към профила на Станислав Гатев

Резултати

  • 7 точки от тестове
  • 0 бонус точки
  • 7 точки общо
  • 27 успешни тест(а)
  • 12 неуспешни тест(а)

Код

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):
return self.filter_phone(self.filter_email(self.text))
def filter_email(self, text):
if self.partially_preserve_email_username:
text = self._sub(r"(?P<retain>[a-zA-Z1-9][a-zA-Z0-9_+.-]{2})" +
r"[a-zA-Z0-9_+.-]{3,198}(?=@" +
Validations.HOSTNAME + r")",
r"\g<retain>[FILTERED]", text)
if self.preserve_email_hostname or self.partially_preserve_email_username:
text = self._sub(r"[a-zA-Z1-9][a-zA-Z0-9_+.-]{0,200}(?=@" +
Validations.HOSTNAME + r")", r"[FILTERED]", text)
return self._sub(Validations.EMAIL, r"[EMAIL]", text)
def filter_phone(self, text):
if self.preserve_phone_country_code:
text = self._sub(r"(?P<code>(00|\+)[1-9][0-9]{0,2})" +
r"([ \-\(\)]{0,2}[0-9]){6,11}",
r"\g<code> [FILTERED]", text)
return self._sub(Validations.PHONE, r"[PHONE]", text)
def _sub(self, pattern, value, text):
return re.sub(pattern, value, text)
class Validations:
DOMAIN = r"[0-9a-zA-Z][0-9a-zA-Z-]{0,61}[0-9a-zA-Z]?"
HOSTNAME = r"(" + DOMAIN + "\.)+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})?"
BYTE = r"([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"
IP_ADDRESS = r"{0}\.{0}\.{0}\.{0}".format(BYTE)
EMAIL = r"[a-zA-Z1-9][a-zA-Z0-9_+.-]{0,200}@" + HOSTNAME
PHONE = r"(0|(00|\+)[1-9][0-9]{0,2})([ \-\(\)]{0,2}[0-9]){6,11}"
DATE = r"[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])"
TIME = r"([0-1][0-9]|2[0-3])(:[0-5][0-9]){2}"
DATETIME = r"{0} {1}".format(DATE, TIME)
INTEGER = r"-?(0|[1-9][0-9])*"
NUMBER = INTEGER + r"(\.[0-9]+)?"
@classmethod
def is_email(cls, value):
return cls.is_valid(cls.EMAIL, value)
@classmethod
def is_phone(cls, value):
return cls.is_valid(cls.PHONE, value)
@classmethod
def is_hostname(cls, value):
return cls.is_valid(cls.HOSTNAME, value)
@classmethod
def is_ip_address(cls, value):
return cls.is_valid(cls.IP_ADDRESS, value)
@classmethod
def is_date(cls, value):
return cls.is_valid(cls.DATE, value)
@classmethod
def is_time(cls, value):
return cls.is_valid(cls.TIME, value)
@classmethod
def is_datetime(cls, value):
return cls.is_valid(cls.DATETIME, value)
@classmethod
def is_integer(cls, value):
return cls.is_valid(cls.INTEGER, value)
@classmethod
def is_number(cls, value):
return cls.is_valid(cls.NUMBER, value)
@staticmethod
def is_valid(pattern, value):
return re.match(r"^{0}$".format(pattern), value) is not None

Лог от изпълнението

...FF...........F.....FF..FF...FF.FFF..
======================================================================
FAIL: test_does_not_filter_invalid_emails (test.PrivacyFilterTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-1s7xfs0/test.py", line 48, in test_does_not_filter_invalid_emails
    self.assertEqual(text, solution.PrivacyFilter(text).filtered())
AssertionError: 'Contact me here: _invalid@email.com' != 'Contact me here: _[EMAIL]'
- Contact me here: _invalid@email.com
+ Contact me here: _[EMAIL]


======================================================================
FAIL: test_does_not_filter_invalid_phone_numbers (test.PrivacyFilterTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-1s7xfs0/test.py", line 86, in test_does_not_filter_invalid_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '+1555 123, 55555' != '[PHONE], 55555'
- +1555 123, 55555
+ [PHONE], 55555


======================================================================
FAIL: test_can_validate_more_complex_phone_numbers (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-1s7xfs0/test.py", line 160, in test_can_validate_more_complex_phone_numbers
    self.assertIs(solution.Validations.is_phone(phone), valid)
AssertionError: True is not False

======================================================================
FAIL: test_handles_multiline_strings_in_IP_validation_properly (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-1s7xfs0/test.py", line 189, in test_handles_multiline_strings_in_IP_validation_properly
    self.assertFalse(solution.Validations.is_ip_address("8.8.8.8\n"))
AssertionError: True is not false

======================================================================
FAIL: test_handles_multiline_strings_in_hostname_validation_properly (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-1s7xfs0/test.py", line 179, in test_handles_multiline_strings_in_hostname_validation_properly
    self.assertFalse(solution.Validations.is_hostname("foo.com\n"))
AssertionError: True is not false

======================================================================
FAIL: test_handles_newlines_in_date_validation (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-1s7xfs0/test.py", line 259, in test_handles_newlines_in_date_validation
    self.assertFalse(solution.Validations.is_date("2012-11-19\n"))
AssertionError: True is not false

======================================================================
FAIL: test_handles_newlines_in_time_and_datetime_validation (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-1s7xfs0/test.py", line 288, in test_handles_newlines_in_time_and_datetime_validation
    self.assertFalse(solution.Validations.is_time("12:01:01\n"))
AssertionError: True is not false

======================================================================
FAIL: test_validates_datetime_values (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-1s7xfs0/test.py", line 278, in test_validates_datetime_values
    self.assertTrue(solution.Validations.is_datetime('2012-11-19T19:00:00'))
AssertionError: False is not true

======================================================================
FAIL: test_validates_hostnames (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-1s7xfs0/test.py", line 174, in test_validates_hostnames
    self.assertFalse(solution.Validations.is_hostname('not-a-hostname-.com'))
AssertionError: True is not false

======================================================================
FAIL: test_validates_more_complex_integers (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-1s7xfs0/test.py", line 225, in test_validates_more_complex_integers
    self.assertFalse(solution.Validations.is_integer('00'))
AssertionError: True is not false

======================================================================
FAIL: test_validates_more_complex_numbers (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-1s7xfs0/test.py", line 205, in test_validates_more_complex_numbers
    self.assertFalse(solution.Validations.is_number('00'))
AssertionError: True is not false

======================================================================
FAIL: test_validates_numbers (test.ValidationsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140513-11348-1s7xfs0/test.py", line 197, in test_validates_numbers
    self.assertTrue(solution.Validations.is_number('9'))
AssertionError: False is not true

----------------------------------------------------------------------
Ran 39 tests in 0.056s

FAILED (failures=12)

История (1 версия и 0 коментара)

Станислав обнови решението на 23.04.2014 16:59 (преди около 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):
+ return self.filter_phone(self.filter_email(self.text))
+
+ def filter_email(self, text):
+ if self.partially_preserve_email_username:
+ text = self._sub(r"(?P<retain>[a-zA-Z1-9][a-zA-Z0-9_+.-]{2})" +
+ r"[a-zA-Z0-9_+.-]{3,198}(?=@" +
+ Validations.HOSTNAME + r")",
+ r"\g<retain>[FILTERED]", text)
+ if self.preserve_email_hostname or self.partially_preserve_email_username:
+ text = self._sub(r"[a-zA-Z1-9][a-zA-Z0-9_+.-]{0,200}(?=@" +
+ Validations.HOSTNAME + r")", r"[FILTERED]", text)
+ return self._sub(Validations.EMAIL, r"[EMAIL]", text)
+
+ def filter_phone(self, text):
+ if self.preserve_phone_country_code:
+ text = self._sub(r"(?P<code>(00|\+)[1-9][0-9]{0,2})" +
+ r"([ \-\(\)]{0,2}[0-9]){6,11}",
+ r"\g<code> [FILTERED]", text)
+ return self._sub(Validations.PHONE, r"[PHONE]", text)
+
+ def _sub(self, pattern, value, text):
+ return re.sub(pattern, value, text)
+
+
+class Validations:
+ DOMAIN = r"[0-9a-zA-Z][0-9a-zA-Z-]{0,61}[0-9a-zA-Z]?"
+ HOSTNAME = r"(" + DOMAIN + "\.)+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})?"
+ BYTE = r"([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"
+ IP_ADDRESS = r"{0}\.{0}\.{0}\.{0}".format(BYTE)
+ EMAIL = r"[a-zA-Z1-9][a-zA-Z0-9_+.-]{0,200}@" + HOSTNAME
+ PHONE = r"(0|(00|\+)[1-9][0-9]{0,2})([ \-\(\)]{0,2}[0-9]){6,11}"
+ DATE = r"[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])"
+ TIME = r"([0-1][0-9]|2[0-3])(:[0-5][0-9]){2}"
+ DATETIME = r"{0} {1}".format(DATE, TIME)
+ INTEGER = r"-?(0|[1-9][0-9])*"
+ NUMBER = INTEGER + r"(\.[0-9]+)?"
+
+ @classmethod
+ def is_email(cls, value):
+ return cls.is_valid(cls.EMAIL, value)
+
+ @classmethod
+ def is_phone(cls, value):
+ return cls.is_valid(cls.PHONE, value)
+
+ @classmethod
+ def is_hostname(cls, value):
+ return cls.is_valid(cls.HOSTNAME, value)
+
+ @classmethod
+ def is_ip_address(cls, value):
+ return cls.is_valid(cls.IP_ADDRESS, value)
+
+ @classmethod
+ def is_date(cls, value):
+ return cls.is_valid(cls.DATE, value)
+
+ @classmethod
+ def is_time(cls, value):
+ return cls.is_valid(cls.TIME, value)
+
+ @classmethod
+ def is_datetime(cls, value):
+ return cls.is_valid(cls.DATETIME, value)
+
+ @classmethod
+ def is_integer(cls, value):
+ return cls.is_valid(cls.INTEGER, value)
+
+ @classmethod
+ def is_number(cls, value):
+ return cls.is_valid(cls.NUMBER, value)
+
+ @staticmethod
+ def is_valid(pattern, value):
+ return re.match(r"^{0}$".format(pattern), value) is not None