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

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

Към профила на Виктор Иванов

Резултати

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

Код

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 preserve_username(self, match):
if len(match.group('username')) < 6:
return '[FILTERED]@' + match.group('hostname')
return match.group('username')[:3] + '[FILTERED]@' + match.group('hostname')
def preserve_country_code(self, match):
if match.group('international') is not None:
return match.group('international') + ' [FILTERED]'
return '[PHONE]'
def filtered(self):
username = r'(?P<username>[a-zA-Z0-9][a-zA-Z0-9_\+\.-]{0,200})'
hostname = r'(?P<hostname>([0-9a-zA-Z][0-9a-zA-Z-]{0,61}[0-9a-zA-Z]?\.)+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})?)'
email = username + '@' + hostname
prefix = r'((?<=[^a-zA-Z0-9\+])0(?=[^0])|(?P<international>(\b00|\+)[1-9][0-9]{0,2}))'
number = r'([ ()-]{0,2}[0-9]){6,11}'
phone = prefix + number
if self.partially_preserve_email_username:
result = re.sub(email, self.preserve_username, self.text)
elif self.preserve_email_hostname:
result = re.sub(email, r'[FILTERED]@\g<hostname>', self.text)
else:
result = re.sub(email, '[EMAIL]', self.text)
if self.preserve_phone_country_code:
result = re.sub(phone, self.preserve_country_code, result)
else:
result = re.sub(phone, '[PHONE]', result)
return result
class Validations:
@classmethod
def is_email(cls, value):
username = r'[a-zA-Z0-9][a-zA-Z0-9_\+\.-]{0,200}'
hostname = r'([0-9a-zA-Z][0-9a-zA-Z-]{0,61}[0-9a-zA-Z]?\.)+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})?'
email = username + '@' + hostname + r'$'
return re.match(email, value) is not None
@classmethod
def is_phone(cls, value):
prefix = r'(0(?=[^0])|(00|\+)[1-9][0-9]{0,2})'
number = r'([ ()-]{0,2}[0-9]){6,11}'
phone = prefix + number + r'$'
return re.match(phone, value) is not None
@classmethod
def is_hostname(cls, value):
hostname = r'([0-9a-zA-Z][0-9a-zA-Z-]{0,61}[0-9a-zA-Z]?\.)+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})?$'
return re.match(hostname, value) is not None
@classmethod
def is_ip_address(cls, value):
octet = r'(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])'
ip_address = octet + r'\.' + octet + r'\.' + octet + r'\.' + octet + r'$'
return re.match(ip_address, value) is not None
@classmethod
def is_number(cls, value):
number = r'-?(0|[1-9][0-9]*(\.[0-9]+)?)$'
return re.match(number, value) is not None
@classmethod
def is_integer(cls, value):
integer = r'-?(0|[1-9][0-9]*)$'
return re.match(integer, value) is not None
@classmethod
def is_date(cls, value):
date = r'[0-9]{4}-(0[0-9]|1[0-2])-([0-2][0-9]|3[01])$'
return re.match(date, value) is not None
@classmethod
def is_time(cls, value):
time = r'([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$'
return re.match(time, value) is not None
@classmethod
def is_datetime(cls, value):
date = r'[0-9]{4}-(0[0-9]|1[0-2])-([0-2][0-9]|3[01])'
time = r'([01][0-9]|[2[0-3]):[0-5][0-9]:[0-5][0-9]'
datetime = date + r'[ T]' + time + r'$'
return re.match(datetime, value) is not None

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

...FF...........F..F..FF..FF...FF..F...
======================================================================
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-156cozw/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-156cozw/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_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-156cozw/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_allow_zero_months_or_days_in_dates (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-156cozw/test.py", line 249, in test_does_not_allow_zero_months_or_days_in_dates
    self.assertFalse(solution.Validations.is_date('1000-00-01'))
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-156cozw/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-156cozw/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-156cozw/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-156cozw/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-156cozw/test.py", line 280, in test_validates_datetime_values
    self.assertTrue(solution.Validations.is_datetime('9999-11-19T23:59: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-156cozw/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_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-156cozw/test.py", line 202, in test_validates_more_complex_numbers
    self.assertTrue(solution.Validations.is_number('0.5555550555555555'))
AssertionError: False is not true

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

FAILED (failures=11)

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

Виктор обнови решението на 23.04.2014 14:21 (преди над 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 preserve_username(self, match):
+ if len(match.group('username')) < 6:
+ return '[FILTERED]@' + match.group('hostname')
+ return match.group('username')[:3] + '[FILTERED]@' + match.group('hostname')
+
+ def preserve_country_code(self, match):
+ if match.group('international') is not None:
+ return match.group('international') + ' [FILTERED]'
+ return '[PHONE]'
+
+ def filtered(self):
+ username = r'(?P<username>[a-zA-Z0-9][a-zA-Z0-9_\+\.-]{0,200})'
+ hostname = r'(?P<hostname>([0-9a-zA-Z][0-9a-zA-Z-]{0,61}[0-9a-zA-Z]?\.)+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})?)'
+ email = username + '@' + hostname
+ prefix = r'((?<=[^a-zA-Z0-9\+])0(?=[^0])|(?P<international>(\b00|\+)[1-9][0-9]{0,2}))'
+ number = r'([ ()-]{0,2}[0-9]){6,11}'
+ phone = prefix + number
+ if self.partially_preserve_email_username:
+ result = re.sub(email, self.preserve_username, self.text)
+ elif self.preserve_email_hostname:
+ result = re.sub(email, r'[FILTERED]@\g<hostname>', self.text)
+ else:
+ result = re.sub(email, '[EMAIL]', self.text)
+ if self.preserve_phone_country_code:
+ result = re.sub(phone, self.preserve_country_code, result)
+ else:
+ result = re.sub(phone, '[PHONE]', result)
+ return result
+
+
+class Validations:
+ @classmethod
+ def is_email(cls, value):
+ username = r'[a-zA-Z0-9][a-zA-Z0-9_\+\.-]{0,200}'
+ hostname = r'([0-9a-zA-Z][0-9a-zA-Z-]{0,61}[0-9a-zA-Z]?\.)+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})?'
+ email = username + '@' + hostname + r'$'
+ return re.match(email, value) is not None
+
+ @classmethod
+ def is_phone(cls, value):
+ prefix = r'(0(?=[^0])|(00|\+)[1-9][0-9]{0,2})'
+ number = r'([ ()-]{0,2}[0-9]){6,11}'
+ phone = prefix + number + r'$'
+ return re.match(phone, value) is not None
+
+ @classmethod
+ def is_hostname(cls, value):
+ hostname = r'([0-9a-zA-Z][0-9a-zA-Z-]{0,61}[0-9a-zA-Z]?\.)+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})?$'
+ return re.match(hostname, value) is not None
+
+ @classmethod
+ def is_ip_address(cls, value):
+ octet = r'(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])'
+ ip_address = octet + r'\.' + octet + r'\.' + octet + r'\.' + octet + r'$'
+ return re.match(ip_address, value) is not None
+
+ @classmethod
+ def is_number(cls, value):
+ number = r'-?(0|[1-9][0-9]*(\.[0-9]+)?)$'
+ return re.match(number, value) is not None
+
+ @classmethod
+ def is_integer(cls, value):
+ integer = r'-?(0|[1-9][0-9]*)$'
+ return re.match(integer, value) is not None
+
+ @classmethod
+ def is_date(cls, value):
+ date = r'[0-9]{4}-(0[0-9]|1[0-2])-([0-2][0-9]|3[01])$'
+ return re.match(date, value) is not None
+
+ @classmethod
+ def is_time(cls, value):
+ time = r'([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$'
+ return re.match(time, value) is not None
+
+ @classmethod
+ def is_datetime(cls, value):
+ date = r'[0-9]{4}-(0[0-9]|1[0-2])-([0-2][0-9]|3[01])'
+ time = r'([01][0-9]|[2[0-3]):[0-5][0-9]:[0-5][0-9]'
+ datetime = date + r'[ T]' + time + r'$'
+ return re.match(datetime, value) is not None