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

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

Към профила на Моника Димитрова

Резултати

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

Код

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):
self.filter_email()
self.filter_phone()
return self.text
def filter_email(self):
substitute = "[FILTERED]"
if self.partially_preserve_email_username is True:
pattern = "(?<=^...)(.*)(?=@)"
elif self.preserve_email_hostname is True:
pattern = "[a-zA-Z0-9][\w+.-]{,200}(?=@)"
else:
pattern = "[a-zA-Z0-9][\w+.-]{,200}@"
pattern += "((?!-)[a-zA-Z\d-]{1,63}(?<!-)\.)+"
pattern += "[a-zA-Z]{2,3}(\.[a-zA-Z]{2,3})?"
substitute = "[EMAIL]"
self.text = re.sub(pattern, substitute, self.text)
def filter_phone(self):
prefix_match = re.match(r'^(00|\+)[1-9]\d{,2}', self.text)
if prefix_match:
pattern = "((?<=^(\+|00)[1-9]\d{,2})(.*))"
substitute = " [FILTERED]"
else:
pattern = "0[1-9]([ \-\(\)]{,2}\d){5,11}"
substitute = "[PHONE]"
self.text = re.sub(pattern, substitute, self.text)
class Validations:
@classmethod
def is_email(cls, value):
username_pattern = re.compile("[a-zA-Z0-9][\w+.-]{,200}@")
username_match = re.match(username_pattern, value)
if username_match:
start, end = username_match.span()
return Validations.is_hostname(value[end:])
return False
@classmethod
def is_phone(cls, value):
prefix_pattern = re.compile("(00|\+)(?!0)\d{1,3}|(0{1})")
prefix_match = re.match(prefix_pattern, value)
if prefix_match:
start, end = prefix_match.span()
pattern = "[1-9]([ \-\(\)]{,2}\d){5,11}"
return Validations.is_match(pattern, value[end:])
return False
@classmethod
def is_hostname(cls, value):
pattern = "((?!-)[A-Z\d-]{1,63}(?<!-)\.)+[A-Z]{2,3}(\.[A-Z]{2,3})?"
return Validations.is_match(pattern, value)
@classmethod
def is_ip_address(cls, value):
pattern = "(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})\.){3}"
pattern += "(?:25[0-5]|2[0-4]\d|[01]?\d{1,9})"
return Validations.is_match(pattern, value)
@classmethod
def is_number(cls, value):
pattern = "-?((0|[1-9]\d*)\.\d+)|(0|[1-9]\d*)"
return Validations.is_match(pattern, value)
@classmethod
def is_integer(cls, value):
pattern = "-?(0|[1-9]\d*)"
return Validations.is_match(pattern, value)
@classmethod
def is_date(cls, value):
pattern = "\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])"
return Validations.is_match(pattern, value)
@classmethod
def is_time(cls, value):
pattern = "([0-1]\d|2[0-3]):[0-5]\d:[0-5]\d"
return Validations.is_match(pattern, value)
@classmethod
def is_datetime(cls, value):
if Validations.is_date(value[0:10]):
if Validations.is_match("( |T)", value[10]):
return Validations.is_time(value[11:19])
return False
@staticmethod
def is_match(pattern_string, value):
pattern = re.compile(pattern_string, re.IGNORECASE)
if re.match(pattern, value):
return True
return False
print(Validations.is_email('foo@bar.com'))

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

True
..FFFEF..FF....FF...FFFFFFFF....F.FF...
======================================================================
ERROR: 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-13lnzqm/test.py", line 76, in test_filters_more_complex_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
  File "/tmp/d20140513-11348-13lnzqm/solution.py", line 13, in filtered
    self.filter_phone()
  File "/tmp/d20140513-11348-13lnzqm/solution.py", line 37, in filter_phone
    self.text = re.sub(pattern, substitute, self.text)
  File "/opt/python3.3/lib/python3.3/re.py", line 170, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/opt/python3.3/lib/python3.3/functools.py", line 258, in wrapper
    result = user_function(*args, **kwds)
  File "/opt/python3.3/lib/python3.3/re.py", line 274, in _compile
    return sre_compile.compile(pattern, flags)
  File "/opt/python3.3/lib/python3.3/sre_compile.py", line 497, in compile
    code = _code(p, flags)
  File "/opt/python3.3/lib/python3.3/sre_compile.py", line 482, in _code
    _compile(code, p.data, flags)
  File "/opt/python3.3/lib/python3.3/sre_compile.py", line 101, in _compile
    _compile(code, av[1], flags)
  File "/opt/python3.3/lib/python3.3/sre_compile.py", line 115, in _compile
    raise error("look-behind requires fixed-width pattern")
sre_constants.error: look-behind requires fixed-width pattern

======================================================================
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-13lnzqm/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' != 'За [FILTERED]@example.com'
- За връзка: [FILTERED]@example.com
?   --------
+ За [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-13lnzqm/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-13lnzqm/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_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-13lnzqm/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@example.com'
- [FILTERED]@example.com
+ me@example.com


======================================================================
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-13lnzqm/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-13lnzqm/test.py", line 100, in test_separates_preserved_country_code_from_filtered_phone_with_a_space
    self.assertEqual(filtered, filter.filtered())
AssertionError: 'Phone: +25 [FILTERED]' != 'Phone: +25( 55 )12 12255'
- Phone: +25 [FILTERED]
+ Phone: +25( 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-13lnzqm/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-13lnzqm/test.py", line 160, in test_can_validate_more_complex_phone_numbers
    self.assertIs(solution.Validations.is_phone(phone), valid)
AssertionError: False is not True

======================================================================
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-13lnzqm/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_does_not_break_on_phones_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-13lnzqm/test.py", line 163, in test_does_not_break_on_phones_in_multiline_strings
    self.assertFalse(solution.Validations.is_phone("0885123123\nwat?"))
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-13lnzqm/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-13lnzqm/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_multiline_strings_in_integer_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-13lnzqm/test.py", line 233, in test_handles_multiline_strings_in_integer_validation_properly
    self.assertFalse(solution.Validations.is_number("42\n24"))
AssertionError: True is not false

======================================================================
FAIL: test_handles_multiline_strings_in_numbers_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-13lnzqm/test.py", line 215, in test_handles_multiline_strings_in_numbers_validation_properly
    self.assertFalse(solution.Validations.is_number("42\n24"))
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-13lnzqm/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-13lnzqm/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_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-13lnzqm/test.py", line 176, in test_validates_hostnames
    self.assertFalse(solution.Validations.is_hostname('not-a-hostname.com.12'))
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-13lnzqm/test.py", line 224, in test_validates_more_complex_integers
    self.assertFalse(solution.Validations.is_integer('-42 '))
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-13lnzqm/test.py", line 205, in test_validates_more_complex_numbers
    self.assertFalse(solution.Validations.is_number('00'))
AssertionError: True is not false

----------------------------------------------------------------------
Ran 39 tests in 0.048s

FAILED (failures=19, errors=1)

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

Моника обнови решението на 23.04.2014 02:20 (преди около 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):
+ self.filter_email()
+ self.filter_phone()
+ return self.text
+
+ def filter_email(self):
+ substitute = "[FILTERED]"
+ if self.partially_preserve_email_username is True:
+ pattern = "(?<=^...)(.*)(?=@)"
+ elif self.preserve_email_hostname is True:
+ pattern = "[a-zA-Z0-9][\w+.-]{,200}(?=@)"
+ else:
+ pattern = "[a-zA-Z0-9][\w+.-]{,200}@"
+ pattern += "((?!-)[a-zA-Z\d-]{1,63}(?<!-)\.)+"
+ pattern += "[a-zA-Z]{2,3}(\.[a-zA-Z]{2,3})?"
+ substitute = "[EMAIL]"
+ self.text = re.sub(pattern, substitute, self.text)
+
+ def filter_phone(self):
+ prefix_match = re.match(r'^(00|\+)[1-9]\d{,2}', self.text)
+ if prefix_match:
+ pattern = "((?<=^(\+|00)[1-9]\d{,2})(.*))"
+ substitute = " [FILTERED]"
+ else:
+ pattern = "0[1-9]([ \-\(\)]{,2}\d){5,11}"
+ substitute = "[PHONE]"
+ self.text = re.sub(pattern, substitute, self.text)
+
+
+class Validations:
+
+ @classmethod
+ def is_email(cls, value):
+ username_pattern = re.compile("[a-zA-Z0-9][\w+.-]{,200}@")
+ username_match = re.match(username_pattern, value)
+ if username_match:
+ start, end = username_match.span()
+ return Validations.is_hostname(value[end:])
+ return False
+
+ @classmethod
+ def is_phone(cls, value):
+ prefix_pattern = re.compile("(00|\+)(?!0)\d{1,3}|(0{1})")
+ prefix_match = re.match(prefix_pattern, value)
+ if prefix_match:
+ start, end = prefix_match.span()
+ pattern = "[1-9]([ \-\(\)]{,2}\d){5,11}"
+ return Validations.is_match(pattern, value[end:])
+ return False
+
+ @classmethod
+ def is_hostname(cls, value):
+ pattern = "((?!-)[A-Z\d-]{1,63}(?<!-)\.)+[A-Z]{2,3}(\.[A-Z]{2,3})?"
+ return Validations.is_match(pattern, value)
+
+ @classmethod
+ def is_ip_address(cls, value):
+ pattern = "(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})\.){3}"
+ pattern += "(?:25[0-5]|2[0-4]\d|[01]?\d{1,9})"
+ return Validations.is_match(pattern, value)
+
+ @classmethod
+ def is_number(cls, value):
+ pattern = "-?((0|[1-9]\d*)\.\d+)|(0|[1-9]\d*)"
+ return Validations.is_match(pattern, value)
+
+ @classmethod
+ def is_integer(cls, value):
+ pattern = "-?(0|[1-9]\d*)"
+ return Validations.is_match(pattern, value)
+
+ @classmethod
+ def is_date(cls, value):
+ pattern = "\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])"
+ return Validations.is_match(pattern, value)
+
+ @classmethod
+ def is_time(cls, value):
+ pattern = "([0-1]\d|2[0-3]):[0-5]\d:[0-5]\d"
+ return Validations.is_match(pattern, value)
+
+ @classmethod
+ def is_datetime(cls, value):
+ if Validations.is_date(value[0:10]):
+ if Validations.is_match("( |T)", value[10]):
+ return Validations.is_time(value[11:19])
+ return False
+
+ @staticmethod
+ def is_match(pattern_string, value):
+ pattern = re.compile(pattern_string, re.IGNORECASE)
+ if re.match(pattern, value):
+ return True
+ return False
+
+print(Validations.is_email('foo@bar.com'))