Решение на Регулярни изрази от Дарина Кръстева

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

Към профила на Дарина Кръстева

Резултати

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

Код

import re
def generate_email_username_regular_expression():
return r"[0-9a-zA-Z][\w+-.]{0,200}"
def generate_email_regular_expression():
return generate_email_username_regular_expression() + r"@" +\
generate_hostname_regular_expression()
def generate_phone_prefix_regular_expression():
return r"((?<!([a-zA-Z]|[+]))0(?!0)|(([+]|00)[1-9][0-9]{0,2}))"
def generate_phone_real_part_regular_expression():
return r"([-( )]{0,2}[0-9]){6,11}"
def generate_phone_number_regular_expression():
return generate_phone_prefix_regular_expression() +\
generate_phone_real_part_regular_expression() + r"$"
def generate_hostname_regular_expression():
domain_or_subdomain_name = r"([0-9a-zA-Z][1-9a-zA-Z-]{0,62}(?<!-)[.])+"
TLD_name = r"[a-zA-Z]{2,3}(([.][a-zA-Z]){2}){0,1}"
return domain_or_subdomain_name + TLD_name + r"$"
def generate_ip_regular_expression():
ip_bytes =\
[r"(((0|([1-9][0-9]{0,1}))|(1[0-9][0-9]))|((2[0-4][0-9])|(25[0-5])))"] * 4
return r"[.]".join(ip_bytes) + r"$"
def generate_integer_regular_expression():
return r"(0|([-]{0,1}[1-9][0-9]*))$"
def generate_number_regular_expression():
return generate_integer_regular_expression()[:-1] + r"([.]([0-9])+)*$"
def generate_time_regular_expression():
return r"(([01][0-9])|(2[0-3])):([0-5][0-9]):([0-5][0-9])$"
def generate_date_regular_expression():
return r"[0-9]{4}-((0[1-9])|1[012])-((0[1-9])|([12][0-9])|(3[01]))$"
def generate_datetime_regular_expression():
return generate_date_regular_expression()[:-1] + r"( |T)" +\
generate_time_regular_expression()
class PrivacyFilter:
def __init__(self, text):
self.text = text
self.filtered_text = ""
self.preserve_phone_country_code = False
self.preserve_email_hostname = False
self.partially_preserve_email_username = False
def filtered(self):
self.filtered_text = self.text
username_regular_expression =\
generate_email_username_regular_expression() + r"@"
if not self.preserve_email_hostname and not\
self.partially_preserve_email_username:
self.filtered_text =\
re.sub(generate_email_regular_expression()[:-1], "[EMAIL]",
self.filtered_text)
elif self.preserve_email_hostname and not\
self.partially_preserve_email_username:
self.filtered_text =\
re.sub(username_regular_expression, "[FILTERED]@",
self.filtered_text)
else:
matches =\
re.findall(username_regular_expression, self.filtered_text)
for match in matches:
if len(match) < 6:
self.filtered_text = self.filtered_text.replace(
match, "[FILTERED]@")
else:
partially_filtered = match[0:3] + "[FILTERED]@"
self.filtered_text =\
self.filtered_text.replace(match, partially_filtered)
if not self.preserve_phone_country_code:
phone_number =\
r"(0(?!0)|((\b[+]|00)[1-9][0-9]{1,2}))([-( )]{0,2}[0-9]){6,11}"
self.filtered_text =\
re.sub(phone_number, "[PHONE]", self.filtered_text)
else:
local_number_regular_expression = r"0" +\
generate_phone_real_part_regular_expression()
self.filtered_text = re.sub(local_number_regular_expression,
"[PHONE]", self.filtered_text)
international_phone_without_code =\
r"(?<=(([+]|00)[1-9][0-9][0-9][0-9]))([-( )]{0,2}[0-9]){6,11}"
self.filtered_text = re.sub(international_phone_without_code,
" [FILTERED]", self.filtered_text)
return self.filtered_text
class Validations:
@classmethod
def is_email(cls, value):
return re.match(generate_email_regular_expression(), value) is not None
@classmethod
def is_phone(cls, value):
return re.match(generate_phone_number_regular_expression(), value) is\
not None
@classmethod
def is_hostname(cls, value):
return re.match(generate_hostname_regular_expression(), value) is\
not None
@classmethod
def is_ip_address(cls, value):
return re.match(generate_ip_regular_expression(), value) is not None
@classmethod
def is_number(cls, value):
return re.match(generate_number_regular_expression(), value) is\
not None
@classmethod
def is_integer(cls, value):
return re.match(generate_integer_regular_expression(), value) is\
not None
@classmethod
def is_date(cls, value):
return re.match(generate_date_regular_expression(), value) is not None
@classmethod
def is_time(cls, value):
return re.match(generate_time_regular_expression(), value) is not None
@classmethod
def is_datetime(cls, value):
return re.match(generate_datetime_regular_expression(), value) is not\
None

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

...FFF...FE.....F.....FF..FF....F.FF...
======================================================================
ERROR: 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-j78gm5/test.py", line 100, in test_separates_preserved_country_code_from_filtered_phone_with_a_space
    self.assertEqual(filtered, filter.filtered())
  File "/tmp/d20140513-11348-j78gm5/solution.py", line 106, in filtered
    " [FILTERED]", self.filtered_text)
  File "/opt/python3.3/lib/python3.3/re.py", line 170, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/opt/python3.3/lib/python3.3/functools.py", line 258, in wrapper
    result = user_function(*args, **kwds)
  File "/opt/python3.3/lib/python3.3/re.py", line 274, in _compile
    return sre_compile.compile(pattern, flags)
  File "/opt/python3.3/lib/python3.3/sre_compile.py", line 497, in compile
    code = _code(p, flags)
  File "/opt/python3.3/lib/python3.3/sre_compile.py", line 482, in _code
    _compile(code, p.data, flags)
  File "/opt/python3.3/lib/python3.3/sre_compile.py", line 115, in _compile
    raise error("look-behind requires fixed-width pattern")
sre_constants.error: look-behind requires fixed-width pattern

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


======================================================================
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-j78gm5/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_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-j78gm5/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-j78gm5/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-j78gm5/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-j78gm5/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-j78gm5/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-j78gm5/test.py", line 171, in test_validates_hostnames
    self.assertTrue(solution.Validations.is_hostname('sub0domain.not-a-hostname.com'))
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-j78gm5/test.py", line 228, in test_validates_more_complex_integers
    self.assertTrue(solution.Validations.is_integer('-0'))
AssertionError: False is not true

======================================================================
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-j78gm5/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.068s

FAILED (failures=12, errors=1)

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

Дарина обнови решението на 23.04.2014 16:00 (преди над 10 години)

+import re
+
+
+def generate_email_username_regular_expression():
+ return r"[0-9a-zA-Z][\w+-.]{0,200}"
+
+
+def generate_email_regular_expression():
+ return generate_email_username_regular_expression() + r"@" +\
+ generate_hostname_regular_expression()
+
+
+def generate_phone_prefix_regular_expression():
+ return r"((?<!([a-zA-Z]|[+]))0(?!0)|(([+]|00)[1-9][0-9]{0,2}))"
+
+
+def generate_phone_real_part_regular_expression():
+ return r"([-( )]{0,2}[0-9]){6,11}"
+
+
+def generate_phone_number_regular_expression():
+ return generate_phone_prefix_regular_expression() +\
+ generate_phone_real_part_regular_expression() + r"$"
+
+
+def generate_hostname_regular_expression():
+ domain_or_subdomain_name = r"([0-9a-zA-Z][1-9a-zA-Z-]{0,62}(?<!-)[.])+"
+ TLD_name = r"[a-zA-Z]{2,3}(([.][a-zA-Z]){2}){0,1}"
+ return domain_or_subdomain_name + TLD_name + r"$"
+
+
+def generate_ip_regular_expression():
+ ip_bytes =\
+ [r"(((0|([1-9][0-9]{0,1}))|(1[0-9][0-9]))|((2[0-4][0-9])|(25[0-5])))"] * 4
+ return r"[.]".join(ip_bytes) + r"$"
+
+
+def generate_integer_regular_expression():
+ return r"(0|([-]{0,1}[1-9][0-9]*))$"
+
+
+def generate_number_regular_expression():
+ return generate_integer_regular_expression()[:-1] + r"([.]([0-9])+)*$"
+
+
+def generate_time_regular_expression():
+ return r"(([01][0-9])|(2[0-3])):([0-5][0-9]):([0-5][0-9])$"
+
+
+def generate_date_regular_expression():
+ return r"[0-9]{4}-((0[1-9])|1[012])-((0[1-9])|([12][0-9])|(3[01]))$"
+
+
+def generate_datetime_regular_expression():
+ return generate_date_regular_expression()[:-1] + r"( |T)" +\
+ generate_time_regular_expression()
+
+
+class PrivacyFilter:
+
+ def __init__(self, text):
+ self.text = text
+ self.filtered_text = ""
+ self.preserve_phone_country_code = False
+ self.preserve_email_hostname = False
+ self.partially_preserve_email_username = False
+
+ def filtered(self):
+ self.filtered_text = self.text
+ username_regular_expression =\
+ generate_email_username_regular_expression() + r"@"
+ if not self.preserve_email_hostname and not\
+ self.partially_preserve_email_username:
+ self.filtered_text =\
+ re.sub(generate_email_regular_expression()[:-1], "[EMAIL]",
+ self.filtered_text)
+ elif self.preserve_email_hostname and not\
+ self.partially_preserve_email_username:
+ self.filtered_text =\
+ re.sub(username_regular_expression, "[FILTERED]@",
+ self.filtered_text)
+ else:
+ matches =\
+ re.findall(username_regular_expression, self.filtered_text)
+ for match in matches:
+ if len(match) < 6:
+ self.filtered_text = self.filtered_text.replace(
+ match, "[FILTERED]@")
+ else:
+ partially_filtered = match[0:3] + "[FILTERED]@"
+ self.filtered_text =\
+ self.filtered_text.replace(match, partially_filtered)
+ if not self.preserve_phone_country_code:
+ phone_number =\
+ r"(0(?!0)|((\b[+]|00)[1-9][0-9]{1,2}))([-( )]{0,2}[0-9]){6,11}"
+ self.filtered_text =\
+ re.sub(phone_number, "[PHONE]", self.filtered_text)
+ else:
+ local_number_regular_expression = r"0" +\
+ generate_phone_real_part_regular_expression()
+ self.filtered_text = re.sub(local_number_regular_expression,
+ "[PHONE]", self.filtered_text)
+ international_phone_without_code =\
+ r"(?<=(([+]|00)[1-9][0-9][0-9][0-9]))([-( )]{0,2}[0-9]){6,11}"
+ self.filtered_text = re.sub(international_phone_without_code,
+ " [FILTERED]", self.filtered_text)
+ return self.filtered_text
+
+
+class Validations:
+
+ @classmethod
+ def is_email(cls, value):
+ return re.match(generate_email_regular_expression(), value) is not None
+
+ @classmethod
+ def is_phone(cls, value):
+ return re.match(generate_phone_number_regular_expression(), value) is\
+ not None
+
+ @classmethod
+ def is_hostname(cls, value):
+ return re.match(generate_hostname_regular_expression(), value) is\
+ not None
+
+ @classmethod
+ def is_ip_address(cls, value):
+ return re.match(generate_ip_regular_expression(), value) is not None
+
+ @classmethod
+ def is_number(cls, value):
+ return re.match(generate_number_regular_expression(), value) is\
+ not None
+
+ @classmethod
+ def is_integer(cls, value):
+ return re.match(generate_integer_regular_expression(), value) is\
+ not None
+
+ @classmethod
+ def is_date(cls, value):
+ return re.match(generate_date_regular_expression(), value) is not None
+
+ @classmethod
+ def is_time(cls, value):
+ return re.match(generate_time_regular_expression(), value) is not None
+
+ @classmethod
+ def is_datetime(cls, value):
+ return re.match(generate_datetime_regular_expression(), value) is not\
+ None