Решение на Регулярни изрази от Лъчезар Николов

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

Към профила на Лъчезар Николов

Резултати

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

Код

import re
from builtins import classmethod
class PrivacyFilter:
def __init__(self, text):
self.__original_text = text[:]
self.preserve_email_hostname = False
self.partially_preserve_email_username = False
self.preserve_phone_country_code = False
def filtered(self):
filtered_text = None
email_pattern = r'([^\W_][\w\.\+-]{0,2})[\w\.\+-]{0,198}(@(?:(?:(?:[' \
r'^\W_]{1,2})|(?:[^\W_][a-zA-Z0-9-]{0,61}[^\W_]))\.)' \
r'+[a-zA-Z]{2,3})'
international_phone_pattern = r'((00|\+)[1-9]\d{1,2})([\\(\\) -]{0,' \
r'2}\d){6,11}'
local_phone_pattern = r'(0|\+)([\\(\\) -]{0,2}\d){6,11}'
if self.partially_preserve_email_username:
filtered_text = re.sub(email_pattern, r'\1[FILTERED]\2',
self.__original_text)
elif self.preserve_email_hostname:
filtered_text = re.sub(email_pattern, r'[FILTERED]\2',
self.__original_text)
else:
filtered_text = re.sub(email_pattern, r'[EMAIL]',
self.__original_text)
if self.preserve_phone_country_code:
filtered_text = re.sub(international_phone_pattern,
r'\1 [FILTERED]',
filtered_text)
else:
filtered_text = re.sub(international_phone_pattern, r'[PHONE]',
filtered_text)
filtered_text = re.sub(local_phone_pattern, r'[PHONE]', filtered_text)
return filtered_text
class Validations:
__hostname_pattern = r'^((([^\W_]{1,2})|([^\W_][a-zA-Z0-9-]{0,61}' \
r'[^\W_]))\.)+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})?$'
__email_pattern = r'^[^\W_][\w\.\+-]' \
r'{{0,200}}@{}'.format(__hostname_pattern[1:])
__telephone_pattern = r'^((0|\+)|((00|\+)[1-9]\d{1,2}))' \
r'([\\(\\) -]{0,2}\d){6,11}$'
__date_pattern = r'^\d{4}-((0[1-9])|(1[0-2]))-((0[1-9])|([12]\d)|(3[01]))$'
__time_pattern = r'^(([01]\d)|(2[0-3])):[0-5]\d:[0-5]\d$'
__integer_pattern = r'^(\+|-)?(0|(?:[1-9]\d*))$'
__number_pattern = r'{}{}$'.format(__integer_pattern[:-1], '(\.\d*)?')
__byte_pattern = r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
__ip_address_pattern = r'^({0}\.){{3}}{0}$'.format(__byte_pattern)
__datetime_pattern = r'{}[T ]' \
r'{}'.format(__date_pattern[:-1], __time_pattern[1:])
def __validate(value, pattern):
matched_string = re.match(pattern, value)
return matched_string is not None
@classmethod
def is_email(cls, value):
return cls.__validate(value, cls.__email_pattern)
@classmethod
def is_phone(cls, value):
return cls.__validate(value, cls.__telephone_pattern)
@classmethod
def is_hostname(cls, value):
return cls.__validate(value, cls.__hostname_pattern)
@classmethod
def is_ip_address(cls, value):
return cls.__validate(value, cls.__ip_address_pattern)
@classmethod
def is_number(cls, value):
return cls.__validate(value, cls.__number_pattern)
@classmethod
def is_integer(cls, value):
return cls.__validate(value, cls.__integer_pattern)
@classmethod
def is_date(cls, value):
return cls.__validate(value, cls.__date_pattern)
@classmethod
def is_time(cls, value):
return cls.__validate(value, cls.__time_pattern)
@classmethod
def is_datetime(cls, value):
return cls.__validate(value, cls.__datetime_pattern)

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

..FFFFF.........F.....FF..FF...........
======================================================================
FAIL: 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-qxlqhd/test.py", line 64, in test_does_not_brake_with_unicode
    self.assertEqual('За връзка: [FILTERED]@example.com', self.partially_filter_email_usernames('За връзка: me@example.com'))
AssertionError: 'За връзка: [FILTERED]@example.com' != 'За връзка: me[FILTERED]@example.com'
- За връзка: [FILTERED]@example.com
+ За връзка: me[FILTERED]@example.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-qxlqhd/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-qxlqhd/test.py", line 86, in test_does_not_filter_invalid_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: 'Reach me at: 0885123' != 'Reach me at: [PHONE]'
- Reach me at: 0885123
+ Reach me at: [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-qxlqhd/test.py", line 76, in test_filters_more_complex_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '[PHONE]' != '[PHONE]9'
- [PHONE]
+ [PHONE]9
?        +


======================================================================
FAIL: 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-qxlqhd/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'))
AssertionError: '[FILTERED]@example.com' != 'me[FILTERED]@example.com'
- [FILTERED]@example.com
+ me[FILTERED]@example.com
? ++


======================================================================
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-qxlqhd/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-qxlqhd/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-qxlqhd/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-qxlqhd/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-qxlqhd/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

----------------------------------------------------------------------
Ran 39 tests in 0.058s

FAILED (failures=10)

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

Лъчезар обнови решението на 23.04.2014 00:31 (преди около 10 години)

+import re
+from builtins import classmethod
+
+
+class PrivacyFilter:
+ def __init__(self, text):
+ self.__original_text = text[:]
+ self.preserve_email_hostname = False
+ self.partially_preserve_email_username = False
+ self.preserve_phone_country_code = False
+
+ def filtered(self):
+ filtered_text = None
+
+ email_pattern = r'([^\W_][\w\.\+-]{0,2})[\w\.\+-]{0,198}(@(?:(?:(?:[' \
+ r'^\W_]{1,2})|(?:[^\W_][a-zA-Z0-9-]{0,61}[^\W_]))\.)' \
+ r'+[a-zA-Z]{2,3})'
+
+ international_phone_pattern = r'((00|\+)[1-9]\d{1,2})([\\(\\) -]{0,' \
+ r'2}\d){6,11}'
+
+ local_phone_pattern = r'(0|\+)([\\(\\) -]{0,2}\d){6,11}'
+
+ if self.partially_preserve_email_username:
+ filtered_text = re.sub(email_pattern, r'\1[FILTERED]\2',
+ self.__original_text)
+ elif self.preserve_email_hostname:
+ filtered_text = re.sub(email_pattern, r'[FILTERED]\2',
+ self.__original_text)
+ else:
+ filtered_text = re.sub(email_pattern, r'[EMAIL]',
+ self.__original_text)
+
+ if self.preserve_phone_country_code:
+ filtered_text = re.sub(international_phone_pattern,
+ r'\1 [FILTERED]',
+ filtered_text)
+ else:
+ filtered_text = re.sub(international_phone_pattern, r'[PHONE]',
+ filtered_text)
+
+ filtered_text = re.sub(local_phone_pattern, r'[PHONE]', filtered_text)
+
+ return filtered_text
+
+
+class Validations:
+ __hostname_pattern = r'^((([^\W_]{1,2})|([^\W_][a-zA-Z0-9-]{0,61}' \
+ r'[^\W_]))\.)+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})?$'
+ __email_pattern = r'^[^\W_][\w\.\+-]' \
+ r'{{0,200}}@{}'.format(__hostname_pattern[1:])
+ __telephone_pattern = r'^((0|\+)|((00|\+)[1-9]\d{1,2}))' \
+ r'([\\(\\) -]{0,2}\d){6,11}$'
+ __date_pattern = r'^\d{4}-((0[1-9])|(1[0-2]))-((0[1-9])|([12]\d)|(3[01]))$'
+ __time_pattern = r'^(([01]\d)|(2[0-3])):[0-5]\d:[0-5]\d$'
+ __integer_pattern = r'^(\+|-)?(0|(?:[1-9]\d*))$'
+ __number_pattern = r'{}{}$'.format(__integer_pattern[:-1], '(\.\d*)?')
+ __byte_pattern = r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
+ __ip_address_pattern = r'^({0}\.){{3}}{0}$'.format(__byte_pattern)
+ __datetime_pattern = r'{}[T ]' \
+ r'{}'.format(__date_pattern[:-1], __time_pattern[1:])
+
+ def __validate(value, pattern):
+ matched_string = re.match(pattern, value)
+ return matched_string is not None
+
+ @classmethod
+ def is_email(cls, value):
+ return cls.__validate(value, cls.__email_pattern)
+
+ @classmethod
+ def is_phone(cls, value):
+ return cls.__validate(value, cls.__telephone_pattern)
+
+ @classmethod
+ def is_hostname(cls, value):
+ return cls.__validate(value, cls.__hostname_pattern)
+
+ @classmethod
+ def is_ip_address(cls, value):
+ return cls.__validate(value, cls.__ip_address_pattern)
+
+ @classmethod
+ def is_number(cls, value):
+ return cls.__validate(value, cls.__number_pattern)
+
+ @classmethod
+ def is_integer(cls, value):
+ return cls.__validate(value, cls.__integer_pattern)
+
+ @classmethod
+ def is_date(cls, value):
+ return cls.__validate(value, cls.__date_pattern)
+
+ @classmethod
+ def is_time(cls, value):
+ return cls.__validate(value, cls.__time_pattern)
+
+ @classmethod
+ def is_datetime(cls, value):
+ return cls.__validate(value, cls.__datetime_pattern)