Решение на Регулярни изрази от Илиян Влахов

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

Към профила на Илиян Влахов

Резултати

  • 6 точки от тестове
  • 0 бонус точки
  • 6 точки общо
  • 22 успешни тест(а)
  • 17 неуспешни тест(а)

Код

import re
INTEGER_PATTERN = r'^(-?[1-9]|-?[1-9]\d+|0)$'
FLOAT_PATTERN = r'^((-?0\.\d+)|(-?[1-9]\d+\.\d+))$'
DATE_PATTERN = r'(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])'
TIME_PATTERN = r'(0\d|1\d|2[0-3]):([0-5][0-9]):([0-5][0-9])'
INTERVAL_PATTERN = r'(\s|T|\sT\s)'
IS_DIGIT_PATTERN = r'(0|[1-9]|[1-9][0-9]|1[0-9]{,2}|2[0-5]{,2})'
DOMAIN_PATTERN = r'([a-zA-Z0-9]\w{,61}[a-zA-Z0-9]\.)+'
TLD_PATTERN = r'[a-zA-Z0-9]{2,3}(\.[a-zA-Z]{2})?'
HOSTNAME_PATTERN = "{0}{1}".format(DOMAIN_PATTERN, TLD_PATTERN)
EMAIL_PATTERN = r'[a-zA-Z0-9][a-zA-Z0-9_+-.]{,200}@'
IS_EMAIL_PATTERN = "{0}{1}".format(EMAIL_PATTERN, HOSTNAME_PATTERN)
IS_PHONE_NUMBER = r'(0[1-9]\d{6,11}|((00|\+)[1-9]\d{1,2}\d{6,11}))$'
PREFIX_PATTERN = r'(00[1-9]\d{1,2}|\+[1-9]\d{1,2}|0)'
class Validations:
@classmethod
def is_email(cls, value):
pattern = IS_EMAIL_PATTERN
return bool(re.search(pattern, value))
@classmethod
def is_hostname(cls, value):
pattern = HOSTNAME_PATTERN
return bool(re.search(pattern, value))
@classmethod
def is_phone(cls, value):
pattern = IS_PHONE_NUMBER
return bool(re.search(pattern, value))
@classmethod
def is_ip_address(cls, value):
pattern = "^{0}.{0}.{0}.{0}$".format(IS_DIGIT_PATTERN)
return bool(len(re.findall(pattern, value)) > 0)
@classmethod
def is_number(cls, value):
pattern = "{0}|{1}".format(INTEGER_PATTERN, FLOAT_PATTERN)
return bool(len(re.findall(pattern, value)) > 0)
@classmethod
def is_integer(cls, value):
pattern = "{0}".format(INTEGER_PATTERN)
return bool(len(re.findall(pattern, value)) > 0)
@classmethod
def is_date(cls, value):
pattern = "^{0}$".format(DATE_PATTERN)
return bool(len(re.findall(pattern, value)) > 0)
@classmethod
def is_time(cls, value):
pattern = "^{0}$".format(TIME_PATTERN)
return bool(len(re.findall(pattern, value)) > 0)
@classmethod
def is_datetime(cls, value):
pattern = "^{0}{1}{2}$".format(DATE_PATTERN, INTERVAL_PATTERN,
TIME_PATTERN)
return bool(len(re.findall(pattern, value)) > 0)
class PrivacyFilter:
preserve_phone_country_code = False
preserve_email_hostname = False
partially_preserve_email_username = False
def __init__(self, text):
self.text = text
def filtered(self):
if Validations.is_email(self.text):
match = re.search(IS_EMAIL_PATTERN, self.text)
start, end = match.span()
match_lenght = len(self.text[start:self.text.index('@')])
if self.preserve_email_hostname:
self.preserve_email_hostname = False
return re.sub(self.text[start:self.text.index('@')],
'[FILTERED]', self.text)
elif self.partially_preserve_email_username:
if match_lenght > 6:
print(match_lenght)
self.partially_preserve_email_username = False
return re.sub(self.text[start+3:self.text.index('@')],
'[FILTERED]', self.text)
else:
self.partially_preserve_email_username = False
return re.sub(self.text[start:self.text.index('@')],
'[FILTERED]', self.text)
else:
return re.sub(self.text[start:end], '[EMAIL]', self.text)
if Validations.is_phone(self.text):
match = re.search(IS_PHONE_NUMBER, self.text)
start, end = match.span()
if self.preserve_phone_country_code:
self.preserve_phone_country_code = False
return self.text[:start] + '[PHONE]' + self.text[end:]
else:
return self.text[:start] + '[PHONE]' + self.text[end:]

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

F..FFF.F.FFF...FF...F.FF..FF....F.F....
======================================================================
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-1loc90f/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-+3@exa.mple.com'
- [FILTERED]@exa.mple.com
+ some12-+3@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-1loc90f/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-1loc90f/test.py", line 86, in test_does_not_filter_invalid_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '95551212' != None

======================================================================
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-1loc90f/test.py", line 76, in test_filters_more_complex_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '[PHONE]' != None

======================================================================
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-1loc90f/test.py", line 37, in test_obfuscates_more_complicated_emails
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '[EMAIL]' != 'some.user+and-more-here@lawn.co.uk'
- [EMAIL]
+ some.user+and-more-here@lawn.co.uk


======================================================================
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-1loc90f/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...' != None

======================================================================
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-1loc90f/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]' != None

======================================================================
FAIL: test_works_with_blank_or_whitespace_strings_and_preserves_whitespace (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-1loc90f/test.py", line 19, in test_works_with_blank_or_whitespace_strings_and_preserves_whitespace
    self.assertEqual('', solution.PrivacyFilter('').filtered())
AssertionError: '' != None

======================================================================
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-1loc90f/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-1loc90f/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-1loc90f/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_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-1loc90f/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-1loc90f/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-1loc90f/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-1loc90f/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-1loc90f/test.py", line 170, in test_validates_hostnames
    self.assertTrue(solution.Validations.is_hostname('x.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-1loc90f/test.py", line 228, in test_validates_more_complex_integers
    self.assertTrue(solution.Validations.is_integer('-0'))
AssertionError: False is not true

----------------------------------------------------------------------
Ran 39 tests in 0.047s

FAILED (failures=17)

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

Илиян обнови решението на 23.04.2014 16:49 (преди над 10 години)

+import re
+INTEGER_PATTERN = r'^(-?[1-9]|-?[1-9]\d+|0)$'
+FLOAT_PATTERN = r'^((-?0\.\d+)|(-?[1-9]\d+\.\d+))$'
+DATE_PATTERN = r'(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])'
+TIME_PATTERN = r'(0\d|1\d|2[0-3]):([0-5][0-9]):([0-5][0-9])'
+INTERVAL_PATTERN = r'(\s|T|\sT\s)'
+IS_DIGIT_PATTERN = r'(0|[1-9]|[1-9][0-9]|1[0-9]{,2}|2[0-5]{,2})'
+DOMAIN_PATTERN = r'([a-zA-Z0-9]\w{,61}[a-zA-Z0-9]\.)+'
+TLD_PATTERN = r'[a-zA-Z0-9]{2,3}(\.[a-zA-Z]{2})?'
+HOSTNAME_PATTERN = "{0}{1}".format(DOMAIN_PATTERN, TLD_PATTERN)
+EMAIL_PATTERN = r'[a-zA-Z0-9][a-zA-Z0-9_+-.]{,200}@'
+IS_EMAIL_PATTERN = "{0}{1}".format(EMAIL_PATTERN, HOSTNAME_PATTERN)
+IS_PHONE_NUMBER = r'(0[1-9]\d{6,11}|((00|\+)[1-9]\d{1,2}\d{6,11}))$'
+PREFIX_PATTERN = r'(00[1-9]\d{1,2}|\+[1-9]\d{1,2}|0)'
+
+
+class Validations:
+
+ @classmethod
+ def is_email(cls, value):
+ pattern = IS_EMAIL_PATTERN
+ return bool(re.search(pattern, value))
+
+ @classmethod
+ def is_hostname(cls, value):
+ pattern = HOSTNAME_PATTERN
+ return bool(re.search(pattern, value))
+
+ @classmethod
+ def is_phone(cls, value):
+ pattern = IS_PHONE_NUMBER
+ return bool(re.search(pattern, value))
+
+ @classmethod
+ def is_ip_address(cls, value):
+ pattern = "^{0}.{0}.{0}.{0}$".format(IS_DIGIT_PATTERN)
+ return bool(len(re.findall(pattern, value)) > 0)
+
+ @classmethod
+ def is_number(cls, value):
+ pattern = "{0}|{1}".format(INTEGER_PATTERN, FLOAT_PATTERN)
+ return bool(len(re.findall(pattern, value)) > 0)
+
+ @classmethod
+ def is_integer(cls, value):
+ pattern = "{0}".format(INTEGER_PATTERN)
+ return bool(len(re.findall(pattern, value)) > 0)
+
+ @classmethod
+ def is_date(cls, value):
+ pattern = "^{0}$".format(DATE_PATTERN)
+ return bool(len(re.findall(pattern, value)) > 0)
+
+ @classmethod
+ def is_time(cls, value):
+ pattern = "^{0}$".format(TIME_PATTERN)
+ return bool(len(re.findall(pattern, value)) > 0)
+
+ @classmethod
+ def is_datetime(cls, value):
+ pattern = "^{0}{1}{2}$".format(DATE_PATTERN, INTERVAL_PATTERN,
+ TIME_PATTERN)
+ return bool(len(re.findall(pattern, value)) > 0)
+
+
+class PrivacyFilter:
+
+ preserve_phone_country_code = False
+ preserve_email_hostname = False
+ partially_preserve_email_username = False
+
+ def __init__(self, text):
+ self.text = text
+
+ def filtered(self):
+ if Validations.is_email(self.text):
+ match = re.search(IS_EMAIL_PATTERN, self.text)
+ start, end = match.span()
+ match_lenght = len(self.text[start:self.text.index('@')])
+ if self.preserve_email_hostname:
+ self.preserve_email_hostname = False
+ return re.sub(self.text[start:self.text.index('@')],
+ '[FILTERED]', self.text)
+ elif self.partially_preserve_email_username:
+ if match_lenght > 6:
+ print(match_lenght)
+ self.partially_preserve_email_username = False
+ return re.sub(self.text[start+3:self.text.index('@')],
+ '[FILTERED]', self.text)
+ else:
+ self.partially_preserve_email_username = False
+ return re.sub(self.text[start:self.text.index('@')],
+ '[FILTERED]', self.text)
+ else:
+ return re.sub(self.text[start:end], '[EMAIL]', self.text)
+ if Validations.is_phone(self.text):
+ match = re.search(IS_PHONE_NUMBER, self.text)
+ start, end = match.span()
+ if self.preserve_phone_country_code:
+ self.preserve_phone_country_code = False
+ return self.text[:start] + '[PHONE]' + self.text[end:]
+ else:
+ return self.text[:start] + '[PHONE]' + self.text[end:]