Решение на Регулярни изрази от Ангел Ангелов

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

Към профила на Ангел Ангелов

Резултати

  • 8 точки от тестове
  • 0 бонус точки
  • 8 точки общо
  • 31 успешни тест(а)
  • 8 неуспешни тест(а)

Код

import re
PHONE = r'''(?P<prefix>((?<![0-9a-zA-Z+])0(?!0)|(00|\+)[1-9][0-9]{0,2}))
(?P<payload>([()\- ]{0,2}[0-9]){5,10}[0-9])'''
IP = r'''\b([0]|[1-9]\d?|[1]\d{2}|2([0-4]\d|5[0-5]))
\.([0]|[1-9]\d?|[1]\d{2}|2([0-4]\d|5[0-5]))
\.([0]|[1-9]\d?|[1]\d{2}|2([0-4]\d|5[0-5]))
\.([0]|[1-9]\d?|[1]\d{2}|2([0-4]\d|5[0-5]))\b'''
HOSTNAME = r'''(([a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]|[a-zA-Z0-9])\.)+
([a-zA-Z]{2,3}(\.[a-zA-Z]{2})?)'''
EMAIL = r'([a-zA-Z0-9][a-zA-Z0-9_+.\-]{0,200})(?P<hostname>@' \
+ HOSTNAME + r')'
EMAIL_LONG = r'''(?P<shortuser>[a-zA-Z0-9][a-zA-Z0-9_+.\-]{2})
(?P<longuser>[a-zA-Z0-9_+.\-]{3,194})(?P<hostname>@''' \
+ HOSTNAME + r')'
DATE = r'([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][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
INTEGER = r'-?(0|[1-9][0-9]*)'
NUMBER = INTEGER + r'(\.[0-9]+)?'
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 self.preserve_phone_country_code:
result = re.sub(PHONE, r'\g<prefix> [FILTERED]',
self._text, flags=re.X)
else:
result = re.sub(PHONE, r'[PHONE]', self._text, flags=re.X)
if self.partially_preserve_email_username:
result = re.sub(EMAIL_LONG,
r'\g<shortuser>[FILTERED]\g<hostname>',
result, flags=re.X)
if (self.preserve_email_hostname
or self.partially_preserve_email_username):
result = re.sub(EMAIL, r'[FILTERED]\g<hostname>',
result, flags=re.X)
else:
result = re.sub(EMAIL, r'[EMAIL]', result, flags=re.X)
return result
class Validations:
@classmethod
def checkmatch(cls, regex, value):
return re.match(r'^' + regex + r'$', value, re.X) is not None
@classmethod
def is_ip_address(cls, value):
return cls.checkmatch(IP, value)
@classmethod
def is_hostname(cls, value):
return cls.checkmatch(HOSTNAME, value)
@classmethod
def is_email(cls, value):
return cls.checkmatch(EMAIL, value)
@classmethod
def is_date(cls, value):
return cls.checkmatch(DATE, value)
@classmethod
def is_time(cls, value):
return cls.checkmatch(TIME, value)
@classmethod
def is_datetime(cls, value):
return cls.checkmatch(DATETIME, value)
@classmethod
def is_integer(cls, value):
return cls.checkmatch(INTEGER, value)
@classmethod
def is_number(cls, value):
return cls.checkmatch(NUMBER, value)
@classmethod
def is_phone(cls, value):
return cls.checkmatch(PHONE, value)

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

...FF....F......F.....FF..FF...........
======================================================================
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-j3pdoo/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-j3pdoo/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_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-j3pdoo/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...' != ' [PHONE]-1 2 or...'
-  [PHONE] or...
+  [PHONE]-1 2 or...
?         ++++


======================================================================
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-j3pdoo/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-j3pdoo/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-j3pdoo/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-j3pdoo/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-j3pdoo/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.053s

FAILED (failures=8)

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

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

+import re
+PHONE = r'''(?P<prefix>((?<![0-9a-zA-Z+])0(?!0)|(00|\+)[1-9][0-9]{0,2}))
+ (?P<payload>([()\- ]{0,2}[0-9]){5,10}[0-9])'''
+IP = r'''\b([0]|[1-9]\d?|[1]\d{2}|2([0-4]\d|5[0-5]))
+ \.([0]|[1-9]\d?|[1]\d{2}|2([0-4]\d|5[0-5]))
+ \.([0]|[1-9]\d?|[1]\d{2}|2([0-4]\d|5[0-5]))
+ \.([0]|[1-9]\d?|[1]\d{2}|2([0-4]\d|5[0-5]))\b'''
+HOSTNAME = r'''(([a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]|[a-zA-Z0-9])\.)+
+ ([a-zA-Z]{2,3}(\.[a-zA-Z]{2})?)'''
+EMAIL = r'([a-zA-Z0-9][a-zA-Z0-9_+.\-]{0,200})(?P<hostname>@' \
+ + HOSTNAME + r')'
+EMAIL_LONG = r'''(?P<shortuser>[a-zA-Z0-9][a-zA-Z0-9_+.\-]{2})
+ (?P<longuser>[a-zA-Z0-9_+.\-]{3,194})(?P<hostname>@''' \
+ + HOSTNAME + r')'
+DATE = r'([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][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
+INTEGER = r'-?(0|[1-9][0-9]*)'
+NUMBER = INTEGER + r'(\.[0-9]+)?'
+
+
+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 self.preserve_phone_country_code:
+ result = re.sub(PHONE, r'\g<prefix> [FILTERED]',
+ self._text, flags=re.X)
+ else:
+ result = re.sub(PHONE, r'[PHONE]', self._text, flags=re.X)
+
+ if self.partially_preserve_email_username:
+ result = re.sub(EMAIL_LONG,
+ r'\g<shortuser>[FILTERED]\g<hostname>',
+ result, flags=re.X)
+
+ if (self.preserve_email_hostname
+ or self.partially_preserve_email_username):
+ result = re.sub(EMAIL, r'[FILTERED]\g<hostname>',
+ result, flags=re.X)
+ else:
+ result = re.sub(EMAIL, r'[EMAIL]', result, flags=re.X)
+ return result
+
+
+class Validations:
+ @classmethod
+ def checkmatch(cls, regex, value):
+ return re.match(r'^' + regex + r'$', value, re.X) is not None
+
+ @classmethod
+ def is_ip_address(cls, value):
+ return cls.checkmatch(IP, value)
+
+ @classmethod
+ def is_hostname(cls, value):
+ return cls.checkmatch(HOSTNAME, value)
+
+ @classmethod
+ def is_email(cls, value):
+ return cls.checkmatch(EMAIL, value)
+
+ @classmethod
+ def is_date(cls, value):
+ return cls.checkmatch(DATE, value)
+
+ @classmethod
+ def is_time(cls, value):
+ return cls.checkmatch(TIME, value)
+
+ @classmethod
+ def is_datetime(cls, value):
+ return cls.checkmatch(DATETIME, value)
+
+ @classmethod
+ def is_integer(cls, value):
+ return cls.checkmatch(INTEGER, value)
+
+ @classmethod
+ def is_number(cls, value):
+ return cls.checkmatch(NUMBER, value)
+
+ @classmethod
+ def is_phone(cls, value):
+ return cls.checkmatch(PHONE, value)