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

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

Към профила на Мариан Ламбовски

Резултати

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

Код

import re
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):
result = self.text
if self.partially_preserve_email_username:
email_pattern = re.compile(r"""\b([a-zA-Z\d][a-zA-Z\d_+.-]{,2})
[a-zA-Z\d_+.-]{,198}@
((([a-zA-Z\d][a-zA-Z\d-]{,62})\.)*[a-zA-Z]{2,3}
(\.[a-zA-Z]{,2})?)\b""", re.X)
result = re.sub(email_pattern, '\g<1>[FILTERED]@\g<2>', result)
elif self.preserve_email_hostname:
email_pattern = re.compile(r"""\b[a-zA-Z\d][a-zA-Z\d_+.-]{,200}@
((([a-zA-Z\d][a-zA-Z\d-]{,62})\.)*[a-zA-Z]{2,3}
(\.[a-zA-Z]{,2})?)\b""", re.X)
result = re.sub(email_pattern, '[FILTERED]@\g<1>', result)
else:
email_pattern = re.compile(r"""\b[a-zA-Z\d][a-zA-Z\d_+.-]{,200}@
(([a-zA-Z\d][a-zA-Z\d-]{,62})\.)*[a-zA-Z]{2,3}
(\.[a-zA-Z]{,2})?\b""", re.X)
result = re.sub(email_pattern, '[EMAIL]', result)
if self.preserve_phone_country_code:
phone_pattern = re.compile(r"""((\b00|\+)[^0][\d]{,2})
[-\ \(\)\d]([-\ \(\)]{,2}\d){5,10}\b""", re.X)
result = re.sub(phone_pattern, '\g<1> [FILTERED]', result)
phone_pattern = re.compile(r"""\b0(?!0)
[-\ \(\)\d]([-\ \(\)]{,2}\d){5,10}\b""", re.X)
result = re.sub(phone_pattern, '[PHONE]', result)
else:
phone_pattern = re.compile(r"""\b0(?!0)
[-\ \(\)\d](?:[-\ \(\)]{,2}\d){4,9}
|
((\b00|\+)[^0][\d]{,2})
[-\ \(\)\d]([-\ \(\)]{,2}\d){5,10}\b""", re.X)
result = re.sub(phone_pattern, '[PHONE]', result)
return result
class Validations:
@classmethod
def is_email(cls, email):
filter = PrivacyFilter(email)
if filter.filtered() == '[EMAIL]':
return True
return False
@classmethod
def is_phone(cls, phone):
filter = PrivacyFilter(phone)
if filter.filtered() == '[PHONE]':
return True
return False
@classmethod
def is_hostname(cls, hostname):
hostname_pattern = re.compile(r"""^([a-zA-Z\d]([a-zA-Z\d-]){,62}\.)*
[a-zA-Z]{2,3}(\.[a-zA-Z]{,2})?$""", re.X)
check = re.match(hostname_pattern, hostname)
if check != None:
return True
return False
@classmethod
def is_ip_address(cls, address):
ip_pattern = r'^\d+\.\d+\.\d+\.\d+$'
check = re.match(ip_pattern, address)
if check != None:
print(check.group())
bytes = address.split('.')
print(bytes)
for number in bytes:
if int(number) > 255:
return False
return True
return False
@classmethod
def is_number(cls, number):
number_pattern = r'^-?(0|[1-9][0-9]*)(\.[0-9]+)?$'
check = re.match(number_pattern, number)
if check != None:
return True
return False
@classmethod
def is_integer(cls, integer):
integer_pattern = r'^-?(0|[1-9][0-9]*)$'
check = re.match(integer_pattern, integer)
if check != None:
return True
return False
@classmethod
def is_date(cls, date):
date_pattern = r'^\d{4,4}-(0[1-9]|1[0-2])-([0-2][0-9]|3[0-1])$'
check = re.match(date_pattern, date)
if check != None:
return True
return False
@classmethod
def is_time(cls, time):
time_pattern = r'^([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$'
check = re.match(time_pattern, time)
if check != None:
return True
return False
@classmethod
def is_datetime(cls, datetime):
patt = re.compile(r"""^\d{4,4}-(0[1-9]|1[0-2])-([0-2][0-9]|3[0-1])
[T\ ]
([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$""", re.X)
check = re.match(patt, datetime)
if check != None:
return True
return False

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

..F.FFF.........F..F..F
Stdout:
8.8.8.8
['8', '8', '8', '8\n']
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-1x6azvy/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_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-1x6azvy/test.py", line 86, in test_does_not_filter_invalid_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '+1555 123, 55555' != '[PHONE], 55555'
- +1555 123, 55555
+ [PHONE], 55555


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


======================================================================
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-1x6azvy/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-1x6azvy/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-1x6azvy/test.py", line 250, in test_does_not_allow_zero_months_or_days_in_dates
    self.assertFalse(solution.Validations.is_date('1000-01-00'))
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-1x6azvy/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

Stdout:
8.8.8.8
['8', '8', '8', '8\n']

======================================================================
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-1x6azvy/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-1x6azvy/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-1x6azvy/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-1x6azvy/test.py", line 282, in test_validates_datetime_values
    self.assertFalse(solution.Validations.is_datetime('2012-01-00T23:59:00'))
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-1x6azvy/test.py", line 174, in test_validates_hostnames
    self.assertFalse(solution.Validations.is_hostname('not-a-hostname-.com'))
AssertionError: True is not false

----------------------------------------------------------------------
Ran 39 tests in 0.055s

FAILED (failures=12)

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

Мариан обнови решението на 23.04.2014 15:54 (преди над 10 години)

+import re
+
+
+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):
+ result = self.text
+ if self.partially_preserve_email_username:
+ email_pattern = re.compile(r"""\b([a-zA-Z\d][a-zA-Z\d_+.-]{,2})
+ [a-zA-Z\d_+.-]{,198}@
+ ((([a-zA-Z\d][a-zA-Z\d-]{,62})\.)*[a-zA-Z]{2,3}
+ (\.[a-zA-Z]{,2})?)\b""", re.X)
+ result = re.sub(email_pattern, '\g<1>[FILTERED]@\g<2>', result)
+ elif self.preserve_email_hostname:
+ email_pattern = re.compile(r"""\b[a-zA-Z\d][a-zA-Z\d_+.-]{,200}@
+ ((([a-zA-Z\d][a-zA-Z\d-]{,62})\.)*[a-zA-Z]{2,3}
+ (\.[a-zA-Z]{,2})?)\b""", re.X)
+ result = re.sub(email_pattern, '[FILTERED]@\g<1>', result)
+ else:
+ email_pattern = re.compile(r"""\b[a-zA-Z\d][a-zA-Z\d_+.-]{,200}@
+ (([a-zA-Z\d][a-zA-Z\d-]{,62})\.)*[a-zA-Z]{2,3}
+ (\.[a-zA-Z]{,2})?\b""", re.X)
+ result = re.sub(email_pattern, '[EMAIL]', result)
+ if self.preserve_phone_country_code:
+ phone_pattern = re.compile(r"""((\b00|\+)[^0][\d]{,2})
+ [-\ \(\)\d]([-\ \(\)]{,2}\d){5,10}\b""", re.X)
+ result = re.sub(phone_pattern, '\g<1> [FILTERED]', result)
+ phone_pattern = re.compile(r"""\b0(?!0)
+ [-\ \(\)\d]([-\ \(\)]{,2}\d){5,10}\b""", re.X)
+ result = re.sub(phone_pattern, '[PHONE]', result)
+ else:
+ phone_pattern = re.compile(r"""\b0(?!0)
+ [-\ \(\)\d](?:[-\ \(\)]{,2}\d){4,9}
+ |
+ ((\b00|\+)[^0][\d]{,2})
+ [-\ \(\)\d]([-\ \(\)]{,2}\d){5,10}\b""", re.X)
+ result = re.sub(phone_pattern, '[PHONE]', result)
+ return result
+
+
+class Validations:
+ @classmethod
+ def is_email(cls, email):
+ filter = PrivacyFilter(email)
+ if filter.filtered() == '[EMAIL]':
+ return True
+ return False
+
+ @classmethod
+ def is_phone(cls, phone):
+ filter = PrivacyFilter(phone)
+ if filter.filtered() == '[PHONE]':
+ return True
+ return False
+
+ @classmethod
+ def is_hostname(cls, hostname):
+ hostname_pattern = re.compile(r"""^([a-zA-Z\d]([a-zA-Z\d-]){,62}\.)*
+ [a-zA-Z]{2,3}(\.[a-zA-Z]{,2})?$""", re.X)
+ check = re.match(hostname_pattern, hostname)
+ if check != None:
+ return True
+ return False
+
+ @classmethod
+ def is_ip_address(cls, address):
+ ip_pattern = r'^\d+\.\d+\.\d+\.\d+$'
+ check = re.match(ip_pattern, address)
+ if check != None:
+ print(check.group())
+ bytes = address.split('.')
+ print(bytes)
+ for number in bytes:
+ if int(number) > 255:
+ return False
+ return True
+ return False
+
+ @classmethod
+ def is_number(cls, number):
+ number_pattern = r'^-?(0|[1-9][0-9]*)(\.[0-9]+)?$'
+ check = re.match(number_pattern, number)
+ if check != None:
+ return True
+ return False
+
+ @classmethod
+ def is_integer(cls, integer):
+ integer_pattern = r'^-?(0|[1-9][0-9]*)$'
+ check = re.match(integer_pattern, integer)
+ if check != None:
+ return True
+ return False
+
+ @classmethod
+ def is_date(cls, date):
+ date_pattern = r'^\d{4,4}-(0[1-9]|1[0-2])-([0-2][0-9]|3[0-1])$'
+ check = re.match(date_pattern, date)
+ if check != None:
+ return True
+ return False
+
+ @classmethod
+ def is_time(cls, time):
+ time_pattern = r'^([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$'
+ check = re.match(time_pattern, time)
+ if check != None:
+ return True
+ return False
+
+ @classmethod
+ def is_datetime(cls, datetime):
+ patt = re.compile(r"""^\d{4,4}-(0[1-9]|1[0-2])-([0-2][0-9]|3[0-1])
+ [T\ ]
+ ([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$""", re.X)
+ check = re.match(patt, datetime)
+ if check != None:
+ return True
+ return False