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

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

Към профила на Никола Ненков

Резултати

  • 4 точки от тестове
  • 0 бонус точки
  • 4 точки общо
  • 16 успешни тест(а)
  • 23 неуспешни тест(а)

Код

# Sorry, I know this is horendlessly buggy and eyesoringly ugly
# and I should commit slow and painful suicide for it.
# This is not how I ussually write code, it's just that I wrote this in
# under an hour. Holidays suck down your time and replace it with stupid!
import re
HOSTNAME = r'([a-zA-z0-9]\w{,61}[a-zA-z0-9]\.)+[a-zA-z]{2,3}(\.[a-zA-z]{2})?'
EMAIL_USERNAME = r'[a-zA-z0-9][-+\.\w]{,200}@'
LOCAL_PHONE = r'0[- \(\)]{,2}[1-9]([- \(\)]{,2}\d){5,10}'
INTERNATIONAL_PREFIX = r'(00|\+[1-9]\d{,2})'
INTERNATIONAL_ACTUAL = r'[- \(\)]{,2}[1-9]([- \(\)]{,2}\d){5,10}'
INTERNATIONAL_PHONE = INTERNATIONAL_PREFIX + INTERNATIONAL_ACTUAL
IP_ADDRESS_PLUS_DOT = r'((\d|\d\d|1\d\d|2[0-4]\d|25[0-5])\.){4}'
NUMBER = r'-?(0|[1-9]\d*)(\.\d+)?'
INTEGER = r'-?(0|[1-9]\d*)'
DATE = r'\d{4}-(0\d|1[12])-([012]\d|3[01])'
TIME = r'([01]\d|2[0-3]):[0-5]\d:[0-5]\d'
class Validations:
@classmethod
def matches_regex(cls, regex, value):
return bool(re.match(regex, value))
@classmethod
def is_hostname(cls, value):
return cls.matches_regex(HOSTNAME, value)
@classmethod
def is_email(cls, value): # might error on invalid email
if '@' not in value or not cls.matches_regex(EMAIL_USERNAME, value):
return False
return cls.is_hostname(value.split('@')[1])
@classmethod
def is_phone(cls, value): # so bad
is_local_phone = cls.matches_regex(LOCAL_PHONE, value)
is_international_phone = cls.matches_regex(INTERNATIONAL_PHONE, value)
return is_local_phone or is_international_phone
@classmethod # what is the equivalent of \g<1> in python?
def is_ip_address(cls, value):
return cls.matches_regex(IP_ADDRESS_PLUS_DOT, value + '.')
@classmethod
def is_number(cls, value):
return cls.matches_regex(NUMBER, value)
@classmethod
def is_integer(cls, value):
return cls.matches_regex(INTEGER, value)
@classmethod
def is_date(cls, value):
return cls.matches_regex(DATE, value)
@classmethod
def is_time(cls, value):
return cls.matches_regex(TIME, value)
@classmethod
def is_datetime(cls, value): # might error on invalid
if len(value) != 19 or value[10] != ' ':
return False
return cls.is_date(value[:10]) and cls.is_time(value[11:])
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):
phone_filtered = PrivacyFilter(self.filtered_phone_country_code())
return phone_filtered.filtered_email(self.preserve_email_hostname)
def filtered_phone_country_code(self):
if self.preserve_phone_country_code:
replaced_international = re.sub('(<?={}{})'.format(
INTERNATIONAL_PREFIX, INTERNATIONAL_ACTUAL),
' [FILTERED]', self.text)
else:
replaced_international = re.sub(
INTERNATIONAL_PHONE, '[PHONE]', self.text)
return re.sub(LOCAL_PHONE, '[PHONE]', self.text)
def filtered_email(self, preserve_email_hostname):
if preserve_email_hostname:
return re.sub(EMAIL_USERNAME, '[FILTERED]@', self.text)
return re.sub(EMAIL_USERNAME + HOSTNAME, '[EMAIL]', self.text)

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

.FFFFFFF.FF....FF..FFF.FFFFF...FF.FF...
======================================================================
FAIL: test_allows_email_usernames_to_be_partially_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-cx82rn/test.py", line 58, in test_allows_email_usernames_to_be_partially_preserved
    self.assertEqual('som[FILTERED]@example.com', self.partially_filter_email_usernames('someone@example.com'))
AssertionError: 'som[FILTERED]@example.com' != '[EMAIL]'
- som[FILTERED]@example.com
+ [EMAIL]


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


======================================================================
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-cx82rn/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-cx82rn/test.py", line 86, in test_does_not_filter_invalid_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '0005551234569' != '00[PHONE]'
- 0005551234569
+ 00[PHONE]


======================================================================
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-cx82rn/test.py", line 76, in test_filters_more_complex_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '[PHONE]' != '0[PHONE]'
- [PHONE]
+ 0[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-cx82rn/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' != '[EMAIL]'
- [FILTERED]@example.com
+ [EMAIL]


======================================================================
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-cx82rn/test.py", line 37, in test_obfuscates_more_complicated_emails
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '[EMAIL]' != 'larodi@x.com'
- [EMAIL]
+ larodi@x.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-cx82rn/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-cx82rn/test.py", line 100, in test_separates_preserved_country_code_from_filtered_phone_with_a_space
    self.assertEqual(filtered, filter.filtered())
AssertionError: 'Phone: 0025 [FILTERED]' != 'Phone: 0[PHONE]'
- Phone: 0025 [FILTERED]
+ Phone: 0[PHONE]


======================================================================
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-cx82rn/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-cx82rn/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-cx82rn/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_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-cx82rn/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-cx82rn/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_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-cx82rn/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-cx82rn/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-cx82rn/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-cx82rn/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-cx82rn/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-cx82rn/test.py", line 278, in test_validates_datetime_values
    self.assertTrue(solution.Validations.is_datetime('2012-11-19T19:00: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-cx82rn/test.py", line 169, in test_validates_hostnames
    self.assertTrue(solution.Validations.is_hostname('1.2.3.4.xip.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-cx82rn/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-cx82rn/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.055s

FAILED (failures=23)

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

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

+# Sorry, I know this is horendlessly buggy and eyesoringly ugly
+# and I should commit slow and painful suicide for it.
+# This is not how I ussually write code, it's just that I wrote this in
+# under an hour. Holidays suck down your time and replace it with stupid!
+
+import re
+
+HOSTNAME = r'([a-zA-z0-9]\w{,61}[a-zA-z0-9]\.)+[a-zA-z]{2,3}(\.[a-zA-z]{2})?'
+EMAIL_USERNAME = r'[a-zA-z0-9][-+\.\w]{,200}@'
+LOCAL_PHONE = r'0[- \(\)]{,2}[1-9]([- \(\)]{,2}\d){5,10}'
+INTERNATIONAL_PREFIX = r'(00|\+[1-9]\d{,2})'
+INTERNATIONAL_ACTUAL = r'[- \(\)]{,2}[1-9]([- \(\)]{,2}\d){5,10}'
+INTERNATIONAL_PHONE = INTERNATIONAL_PREFIX + INTERNATIONAL_ACTUAL
+IP_ADDRESS_PLUS_DOT = r'((\d|\d\d|1\d\d|2[0-4]\d|25[0-5])\.){4}'
+NUMBER = r'-?(0|[1-9]\d*)(\.\d+)?'
+INTEGER = r'-?(0|[1-9]\d*)'
+DATE = r'\d{4}-(0\d|1[12])-([012]\d|3[01])'
+TIME = r'([01]\d|2[0-3]):[0-5]\d:[0-5]\d'
+
+
+class Validations:
+
+ @classmethod
+ def matches_regex(cls, regex, value):
+ return bool(re.match(regex, value))
+
+ @classmethod
+ def is_hostname(cls, value):
+ return cls.matches_regex(HOSTNAME, value)
+
+ @classmethod
+ def is_email(cls, value): # might error on invalid email
+ if '@' not in value or not cls.matches_regex(EMAIL_USERNAME, value):
+ return False
+ return cls.is_hostname(value.split('@')[1])
+
+ @classmethod
+ def is_phone(cls, value): # so bad
+ is_local_phone = cls.matches_regex(LOCAL_PHONE, value)
+ is_international_phone = cls.matches_regex(INTERNATIONAL_PHONE, value)
+ return is_local_phone or is_international_phone
+
+ @classmethod # what is the equivalent of \g<1> in python?
+ def is_ip_address(cls, value):
+ return cls.matches_regex(IP_ADDRESS_PLUS_DOT, value + '.')
+
+ @classmethod
+ def is_number(cls, value):
+ return cls.matches_regex(NUMBER, value)
+
+ @classmethod
+ def is_integer(cls, value):
+ return cls.matches_regex(INTEGER, value)
+
+ @classmethod
+ def is_date(cls, value):
+ return cls.matches_regex(DATE, value)
+
+ @classmethod
+ def is_time(cls, value):
+ return cls.matches_regex(TIME, value)
+
+ @classmethod
+ def is_datetime(cls, value): # might error on invalid
+ if len(value) != 19 or value[10] != ' ':
+ return False
+ return cls.is_date(value[:10]) and cls.is_time(value[11:])
+
+
+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):
+ phone_filtered = PrivacyFilter(self.filtered_phone_country_code())
+ return phone_filtered.filtered_email(self.preserve_email_hostname)
+
+ def filtered_phone_country_code(self):
+ if self.preserve_phone_country_code:
+ replaced_international = re.sub('(<?={}{})'.format(
+ INTERNATIONAL_PREFIX, INTERNATIONAL_ACTUAL),
+ ' [FILTERED]', self.text)
+ else:
+ replaced_international = re.sub(
+ INTERNATIONAL_PHONE, '[PHONE]', self.text)
+
+ return re.sub(LOCAL_PHONE, '[PHONE]', self.text)
+
+ def filtered_email(self, preserve_email_hostname):
+ if preserve_email_hostname:
+ return re.sub(EMAIL_USERNAME, '[FILTERED]@', self.text)
+ return re.sub(EMAIL_USERNAME + HOSTNAME, '[EMAIL]', self.text)