Решение на Регулярни изрази от Филип Митов

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

Към профила на Филип Митов

Резултати

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

Код

import re
class Patterns():
user_name = '[\w\d][\w\d+\.-]{0,198}'
second_level_domain = '([\w\d-]{,60}[\w\d]\.)+'
top_level_domain = '\w{2,3}(\.\w{2,3})?'
hostname = second_level_domain + top_level_domain
email = '\\b' + user_name + '@' + hostname + '\\b'
phone_prefix = '(\\b(?:00\d{1,2}){1}|\\b0[1-9]|\+[1-9]\d{1,2})'
international_prefix = '(\\b(?:00\d{1,2}){1}|\+[1-9]\d{1,2})'
phone_digits = '[-\)\( ]{0,2}(?:\d[-\)\( ]{0,2}){6,10}\d\\b'
international_phone = '('+international_prefix + phone_digits+')'
phone = phone_prefix + phone_digits
ip_octet = '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
ip_address = (ip_octet + '\.') * 3 + ip_octet
number = '-?0$|((^0|^-?[1-9])\d*(\.\d+)?$)'
integer = '-?0$|((^0|^-?[1-9])\d*$)'
date = '\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])'
time = '([01]\d|2[0-3]):[0-5][0-9]:[0-5][0-9]'
date_and_time = date + '( |T)' + time
class Validations(Patterns):
def __init__(self):
pass
def matcher(regex, string):
return False if re.match(regex, string) is None else True
def searcher(regex, string):
return False if re.search(regex, string) is None else True
def is_email(value):
return Validations.searcher(Patterns.email, value)
def is_phone(value):
return Validations.searcher(Patterns.phone, value)
def is_hostname(value):
return Validations.matcher(Patterns.hostname, value)
def is_ip_address(value):
return Validations.matcher(Patterns.ip_address, value)
def is_number(value):
return Validations.matcher(Patterns.number, value)
def is_integer(value):
return Validations.matcher(Patterns.integer, value)
def is_date(value):
return Validations.matcher(Patterns.date, value)
def is_time(value):
return Validations.matcher(Patterns.time, value)
def is_datetime(value):
return Validations.matcher(Patterns.date_and_time, value)
class PrivacyFilter(Patterns):
def __init__(self, value):
self.preserve_phone_country_code = False
self.preserve_email_hostname = False
self.partially_preserve_email_username = False
self.text = value
def filtered(self):
filtered_information = self.text[:]
if self.preserve_email_hostname == False and self.partially_preserve_email_username == False:
filtered_information = re.sub(
Patterns.email, '[EMAIL]', filtered_information
)
elif self.preserve_email_hostname == True and \
self.partially_preserve_email_username == False:
filtered_information = re.sub(
Patterns.user_name+'@', '[FILTERED]@', filtered_information
)
elif self.preserve_email_hostname == False and \
self.partially_preserve_email_username == True:
match = re.findall(Patterns.user_name+'@', filtered_information)
for element in match:
filtered_information = re.sub(
element, element[:3]+'[FILTERED]@', filtered_information
)
elif self.preserve_email_hostname == True and \
self.partially_preserve_email_username == True:
filtered_information = re.sub(
Patterns.user_name+'@', '[FILTERED]@', filtered_information
)
if self.preserve_phone_country_code == True:
all_matches = re.findall(
Patterns.international_phone, filtered_information
)
for one_match in all_matches:
filtered_information = filtered_information.replace(
one_match[0], one_match[1] + ' [FILTERED]'
)
filtered_information = re.sub(
Patterns.phone, '[PHONE]', filtered_information
)
elif self.preserve_phone_country_code == False:
filtered_information = re.sub(
Patterns.phone, '[PHONE]', filtered_information
)
return filtered_information

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

..FFFFF........FF...FFFF..FF....F.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-7exkc5/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_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-7exkc5/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-7exkc5/test.py", line 86, in test_does_not_filter_invalid_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '0005551234569' != '[PHONE]'
- 0005551234569
+ [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-7exkc5/test.py", line 76, in test_filters_more_complex_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '[PHONE]' != '+1 555 123-456'
- [PHONE]
+ +1 555 123-456


======================================================================
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-7exkc5/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_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-7exkc5/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-7exkc5/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_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-7exkc5/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-7exkc5/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_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-7exkc5/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-7exkc5/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-7exkc5/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-7exkc5/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-7exkc5/test.py", line 176, in test_validates_hostnames
    self.assertFalse(solution.Validations.is_hostname('not-a-hostname.com.12'))
AssertionError: True is not false

======================================================================
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-7exkc5/test.py", line 225, in test_validates_more_complex_integers
    self.assertFalse(solution.Validations.is_integer('00'))
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-7exkc5/test.py", line 203, in test_validates_more_complex_numbers
    self.assertTrue(solution.Validations.is_number('-0.5555550555555555'))
AssertionError: False is not true

----------------------------------------------------------------------
Ran 39 tests in 0.044s

FAILED (failures=16)

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

Филип обнови решението на 22.04.2014 18:24 (преди над 10 години)

+import re
+
+
+class Patterns():
+
+ user_name = '[\w\d][\w\d+\.-]{0,198}'
+ second_level_domain = '([\w\d-]{,60}[\w\d]\.)+'
+ top_level_domain = '\w{2,3}(\.\w{2,3})?'
+ hostname = second_level_domain + top_level_domain
+ email = '\\b' + user_name + '@' + hostname + '\\b'
+
+ phone_prefix = '(\\b(?:00\d{1,2}){1}|\\b0[1-9]|\+[1-9]\d{1,2})'
+ international_prefix = '(\\b(?:00\d{1,2}){1}|\+[1-9]\d{1,2})'
+ phone_digits = '[-\)\( ]{0,2}(?:\d[-\)\( ]{0,2}){6,10}\d\\b'
+ international_phone = '('+international_prefix + phone_digits+')'
+ phone = phone_prefix + phone_digits
+
+ ip_octet = '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
+ ip_address = (ip_octet + '\.') * 3 + ip_octet
+
+ number = '-?0$|((^0|^-?[1-9])\d*(\.\d+)?$)'
+
+ integer = '-?0$|((^0|^-?[1-9])\d*$)'
+
+ date = '\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])'
+
+ time = '([01]\d|2[0-3]):[0-5][0-9]:[0-5][0-9]'
+
+ date_and_time = date + '( |T)' + time
+
+
+class Validations(Patterns):
+
+ def __init__(self):
+ pass
+
+ def matcher(regex, string):
+ return False if re.match(regex, string) is None else True
+
+ def searcher(regex, string):
+ return False if re.search(regex, string) is None else True
+
+ def is_email(value):
+ return Validations.searcher(Patterns.email, value)
+
+ def is_phone(value):
+ return Validations.searcher(Patterns.phone, value)
+
+ def is_hostname(value):
+ return Validations.matcher(Patterns.hostname, value)
+
+ def is_ip_address(value):
+ return Validations.matcher(Patterns.ip_address, value)
+
+ def is_number(value):
+ return Validations.matcher(Patterns.number, value)
+
+ def is_integer(value):
+ return Validations.matcher(Patterns.integer, value)
+
+ def is_date(value):
+ return Validations.matcher(Patterns.date, value)
+
+ def is_time(value):
+ return Validations.matcher(Patterns.time, value)
+
+ def is_datetime(value):
+ return Validations.matcher(Patterns.date_and_time, value)
+
+
+class PrivacyFilter(Patterns):
+
+ def __init__(self, value):
+ self.preserve_phone_country_code = False
+ self.preserve_email_hostname = False
+ self.partially_preserve_email_username = False
+ self.text = value
+
+ def filtered(self):
+ filtered_information = self.text[:]
+
+ if self.preserve_email_hostname == False and self.partially_preserve_email_username == False:
+ filtered_information = re.sub(
+ Patterns.email, '[EMAIL]', filtered_information
+ )
+ elif self.preserve_email_hostname == True and \
+ self.partially_preserve_email_username == False:
+ filtered_information = re.sub(
+ Patterns.user_name+'@', '[FILTERED]@', filtered_information
+ )
+ elif self.preserve_email_hostname == False and \
+ self.partially_preserve_email_username == True:
+ match = re.findall(Patterns.user_name+'@', filtered_information)
+ for element in match:
+ filtered_information = re.sub(
+ element, element[:3]+'[FILTERED]@', filtered_information
+ )
+ elif self.preserve_email_hostname == True and \
+ self.partially_preserve_email_username == True:
+ filtered_information = re.sub(
+ Patterns.user_name+'@', '[FILTERED]@', filtered_information
+ )
+
+ if self.preserve_phone_country_code == True:
+ all_matches = re.findall(
+ Patterns.international_phone, filtered_information
+ )
+ for one_match in all_matches:
+ filtered_information = filtered_information.replace(
+ one_match[0], one_match[1] + ' [FILTERED]'
+ )
+ filtered_information = re.sub(
+ Patterns.phone, '[PHONE]', filtered_information
+ )
+ elif self.preserve_phone_country_code == False:
+ filtered_information = re.sub(
+ Patterns.phone, '[PHONE]', filtered_information
+ )
+
+ return filtered_information