Решение на Регулярни изрази от Йордан Дикманов

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

Към профила на Йордан Дикманов

Резултати

  • 5 точки от тестове
  • 0 бонус точки
  • 5 точки общо
  • 20 успешни тест(а)
  • 19 неуспешни тест(а)

Код

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
self.original_text = text
def filtered(self):
if Validations.is_email(self.text):
if self.partially_preserve_email_username:
self.partially_preserve_email_username_f()
else:
self.preserve_email_hostname_f()
if Validations.is_phone(self.text):
self.preserve_phone_country_code_f()
return self.text
def preserve_email_hostname_f(self):
if self.preserve_email_hostname:
pattern = re.compile('(\w+)@')
self.text = pattern.sub("[FILTERED]@", self.text)
else:
pattern = re.compile('(\w+)@(.+)')
self.text = pattern.sub("[EMAIL]", self.text)
def partially_preserve_email_username_f(self):
pattern = re.compile('\w{3}(\w{3}\w+)@')
self.text = self.text.replace(
pattern.search(self.text).group(1), "[FILTERED]")
self.preserve_email_hostname = True
def preserve_phone_country_code_f(self):
pattern = re.compile('[+]?(359)?([0-9]+)')
if self.preserve_phone_country_code:
self.text = self.text.replace(pattern.search(self.text).group(2),
" [FILTERED]")
else:
self.text = pattern.sub("[PHONE]", self.text)
# print(self.text.replace(r.search(self.text).group(2), " [FILTERED]"))
class Validations:
@staticmethod
def is_email(value):
pattern = re.compile('[a-zA-Z0-9](\w|[+.-]){0,200}@')
pattern_hostname = re.compile('@(.+)')
if pattern_hostname.search(value):
hostname = pattern_hostname.search(value).group(1)
is_hostname_true = bool(Validations.is_hostname(hostname))
return bool(pattern.search(value)) and is_hostname_true
@staticmethod
def is_hostname(value):
pattern = re.compile(
'^([a-zA-Z0-9](\w|[-]){0,61}[^-]\.)+([a-zA-Z]){2,3}$')
return bool(pattern.search(value))
@staticmethod
def is_phone(value):
pattern = re.compile(
'(0|((00|[+])[1-9]\d{0,2}))(\s|[,()-])?[1-9]((\s|[,()-])?[0-9]){4,9}\d$')
# print(r.search(self.value).group())
return bool(pattern.search(value))
@staticmethod
def is_ip_address(value):
pattern = re.compile(
'([^-]\d\d?\d?)\.([^-]\d\d?\d?)\.([^-]\d\d?\d?)\.([^-]\d\d?\d?)')
if not bool(pattern.search(value)):
return False
for i in range(1, 5):
if int(pattern.search(value).group(i)) > 255:
return False
return True
@staticmethod
def is_number(value):
pattern = re.compile('^([-]?(0|(0[.]\d+)|([1-9](\d+)?[.]\d+)))$')
return bool(pattern.search(value))
@staticmethod
def is_integer(value):
pattern = re.compile('^(([-]?0)|([-]?[1-9]\d+))$')
return bool(pattern.search(value))
@staticmethod
def is_date(value):
pattern = re.compile('^(\d\d\d\d)-(\d\d)-(\d\d)$')
if not bool(pattern.search(value)):
return False
if int(pattern.search(value).group(2)) not in range(1, 13):
return False
if int(pattern.search(value).group(3)) not in range(1, 32):
return False
return True
@staticmethod
def is_time(value):
pattern = re.compile('^(\d\d):(\d\d):(\d\d)$')
if not bool(pattern.search(value)):
return False
if int(pattern.search(value).group(1)) not in range(0, 24):
return False
for i in range(2, 4):
if int(pattern.search(value).group(i)) not in range(0, 60):
return False
return True
@staticmethod
def is_datetime(value):
pattern = re.compile('(.+)(\s|[A-Z]|[,._()+])(.+)$')
if pattern.search(value):
is_date_value = pattern.search(value).group(1)
is_time_value = pattern.search(value).group(3)
else:
return False
is_data_true = Validations.is_date(is_date_value)
is_time_true = Validations.is_time(is_time_value)
return is_data_true and is_time_true

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

F.EFFFEF.FF....FF...F..F..FF.F..F.F.F..
======================================================================
ERROR: test_does_not_brake_with_unicode (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-1838ixz/test.py", line 64, in test_does_not_brake_with_unicode
    self.assertEqual('За връзка: [FILTERED]@example.com', self.partially_filter_email_usernames('За връзка: me@example.com'))
  File "/tmp/d20140513-11348-1838ixz/test.py", line 16, in partially_filter_email_usernames
    return filter.filtered()
  File "/tmp/d20140513-11348-1838ixz/solution.py", line 16, in filtered
    self.partially_preserve_email_username_f()
  File "/tmp/d20140513-11348-1838ixz/solution.py", line 37, in partially_preserve_email_username_f
    pattern.search(self.text).group(1), "[FILTERED]")
AttributeError: 'NoneType' object has no attribute 'group'

======================================================================
ERROR: test_filters_whole_email_usernames_if_too_short (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-1838ixz/test.py", line 61, in test_filters_whole_email_usernames_if_too_short
    self.assertEqual('[FILTERED]@example.com', self.partially_filter_email_usernames('me@example.com'))
  File "/tmp/d20140513-11348-1838ixz/test.py", line 16, in partially_filter_email_usernames
    return filter.filtered()
  File "/tmp/d20140513-11348-1838ixz/solution.py", line 16, in filtered
    self.partially_preserve_email_username_f()
  File "/tmp/d20140513-11348-1838ixz/solution.py", line 37, in partially_preserve_email_username_f
    pattern.search(self.text).group(1), "[FILTERED]")
AttributeError: 'NoneType' object has no attribute 'group'

======================================================================
FAIL: test_allows_email_hostname_to_be_preserved (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-1838ixz/test.py", line 55, in test_allows_email_hostname_to_be_preserved
    self.assertEqual('[FILTERED]@exa.mple.com', self.filter_email_usernames('some12-+3@exa.mple.com'))
AssertionError: '[FILTERED]@exa.mple.com' != 'some12-+[FILTERED]@exa.mple.com'
- [FILTERED]@exa.mple.com
+ some12-+[FILTERED]@exa.mple.com
? ++++++++


======================================================================
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-1838ixz/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-1838ixz/test.py", line 86, in test_does_not_filter_invalid_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '0005551234569' != '[PHONE]'
- 0005551234569
+ [PHONE]


======================================================================
FAIL: test_filters_more_complex_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-1838ixz/test.py", line 76, in test_filters_more_complex_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '[PHONE]' != '+1 (555) 123-456-99'
- [PHONE]
+ +1 (555) 123-456-99


======================================================================
FAIL: test_obfuscates_more_complicated_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-1838ixz/test.py", line 37, in test_obfuscates_more_complicated_emails
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '[EMAIL]' != 'some.user+and-more-[EMAIL]'
- [EMAIL]
+ some.user+and-more-[EMAIL]


======================================================================
FAIL: test_preserves_whitespace_around_phones (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-1838ixz/test.py", line 89, in test_preserves_whitespace_around_phones
    self.assertEqual(' [PHONE] or...', solution.PrivacyFilter(' +359881212-12-1 2 or...').filtered())
AssertionError: ' [PHONE] or...' != ' +359881212-12-1 2 or...'
-  [PHONE] or...
+  +359881212-12-1 2 or...


======================================================================
FAIL: test_separates_preserved_country_code_from_filtered_phone_with_a_space (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-1838ixz/test.py", line 100, in test_separates_preserved_country_code_from_filtered_phone_with_a_space
    self.assertEqual(filtered, filter.filtered())
AssertionError: 'Phone: 0025 [FILTERED]' != 'Phone: 0025 (55) 12 12255'
- Phone: 0025 [FILTERED]
+ Phone: 0025 (55) 12 12255


======================================================================
FAIL: test_can_validate_more_complex_emails (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-1838ixz/test.py", line 124, in test_can_validate_more_complex_emails
    self.assertIs(solution.Validations.is_email(email), valid)
AssertionError: True is not False

======================================================================
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-1838ixz/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_does_not_break_on_emails_in_multiline_strings (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-1838ixz/test.py", line 127, in test_does_not_break_on_emails_in_multiline_strings
    self.assertFalse(solution.Validations.is_email("foo@bar.com\nwat?"))
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-1838ixz/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-1838ixz/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-1838ixz/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_IP_addresses (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-1838ixz/test.py", line 183, in test_validates_IP_addresses
    self.assertTrue(solution.Validations.is_ip_address('1.2.3.4'))
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-1838ixz/test.py", line 169, in test_validates_hostnames
    self.assertTrue(solution.Validations.is_hostname('1.2.3.4.xip.io'))
AssertionError: False is not true

======================================================================
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-1838ixz/test.py", line 227, in test_validates_more_complex_integers
    self.assertTrue(solution.Validations.is_integer('9'))
AssertionError: False is not true

======================================================================
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-1838ixz/test.py", line 194, in test_validates_numbers
    self.assertTrue(solution.Validations.is_number('42'))
AssertionError: False is not true

----------------------------------------------------------------------
Ran 39 tests in 0.078s

FAILED (failures=17, errors=2)

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

Йордан обнови решението на 22.04.2014 22:04 (преди над 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
+ self.original_text = text
+
+ def filtered(self):
+ if Validations.is_email(self.text):
+ if self.partially_preserve_email_username:
+ self.partially_preserve_email_username_f()
+ else:
+ self.preserve_email_hostname_f()
+
+ if Validations.is_phone(self.text):
+ self.preserve_phone_country_code_f()
+
+ return self.text
+
+ def preserve_email_hostname_f(self):
+ if self.preserve_email_hostname:
+ pattern = re.compile('(\w+)@')
+ self.text = pattern.sub("[FILTERED]@", self.text)
+ else:
+ pattern = re.compile('(\w+)@(.+)')
+ self.text = pattern.sub("[EMAIL]", self.text)
+
+ def partially_preserve_email_username_f(self):
+
+ pattern = re.compile('\w{3}(\w{3}\w+)@')
+ self.text = self.text.replace(
+ pattern.search(self.text).group(1), "[FILTERED]")
+ self.preserve_email_hostname = True
+
+ def preserve_phone_country_code_f(self):
+ pattern = re.compile('[+]?(359)?([0-9]+)')
+ if self.preserve_phone_country_code:
+ self.text = self.text.replace(pattern.search(self.text).group(2),
+ " [FILTERED]")
+ else:
+ self.text = pattern.sub("[PHONE]", self.text)
+ # print(self.text.replace(r.search(self.text).group(2), " [FILTERED]"))
+
+
+class Validations:
+
+ @staticmethod
+ def is_email(value):
+ pattern = re.compile('[a-zA-Z0-9](\w|[+.-]){0,200}@')
+ pattern_hostname = re.compile('@(.+)')
+ if pattern_hostname.search(value):
+ hostname = pattern_hostname.search(value).group(1)
+ is_hostname_true = bool(Validations.is_hostname(hostname))
+ return bool(pattern.search(value)) and is_hostname_true
+
+ @staticmethod
+ def is_hostname(value):
+ pattern = re.compile(
+ '^([a-zA-Z0-9](\w|[-]){0,61}[^-]\.)+([a-zA-Z]){2,3}$')
+
+ return bool(pattern.search(value))
+
+ @staticmethod
+ def is_phone(value):
+ pattern = re.compile(
+ '(0|((00|[+])[1-9]\d{0,2}))(\s|[,()-])?[1-9]((\s|[,()-])?[0-9]){4,9}\d$')
+ # print(r.search(self.value).group())
+ return bool(pattern.search(value))
+
+ @staticmethod
+ def is_ip_address(value):
+ pattern = re.compile(
+ '([^-]\d\d?\d?)\.([^-]\d\d?\d?)\.([^-]\d\d?\d?)\.([^-]\d\d?\d?)')
+
+ if not bool(pattern.search(value)):
+ return False
+ for i in range(1, 5):
+ if int(pattern.search(value).group(i)) > 255:
+ return False
+ return True
+
+ @staticmethod
+ def is_number(value):
+
+ pattern = re.compile('^([-]?(0|(0[.]\d+)|([1-9](\d+)?[.]\d+)))$')
+ return bool(pattern.search(value))
+
+ @staticmethod
+ def is_integer(value):
+ pattern = re.compile('^(([-]?0)|([-]?[1-9]\d+))$')
+ return bool(pattern.search(value))
+
+ @staticmethod
+ def is_date(value):
+ pattern = re.compile('^(\d\d\d\d)-(\d\d)-(\d\d)$')
+ if not bool(pattern.search(value)):
+ return False
+ if int(pattern.search(value).group(2)) not in range(1, 13):
+ return False
+ if int(pattern.search(value).group(3)) not in range(1, 32):
+ return False
+ return True
+
+ @staticmethod
+ def is_time(value):
+ pattern = re.compile('^(\d\d):(\d\d):(\d\d)$')
+ if not bool(pattern.search(value)):
+ return False
+ if int(pattern.search(value).group(1)) not in range(0, 24):
+ return False
+
+ for i in range(2, 4):
+ if int(pattern.search(value).group(i)) not in range(0, 60):
+ return False
+ return True
+
+ @staticmethod
+ def is_datetime(value):
+ pattern = re.compile('(.+)(\s|[A-Z]|[,._()+])(.+)$')
+ if pattern.search(value):
+ is_date_value = pattern.search(value).group(1)
+ is_time_value = pattern.search(value).group(3)
+ else:
+ return False
+ is_data_true = Validations.is_date(is_date_value)
+ is_time_true = Validations.is_time(is_time_value)
+ return is_data_true and is_time_true