Решение на Регулярни изрази от Елена Димитрова

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

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

Резултати

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

Код

import re
class Validations:
@classmethod
def is_email(self, value):
email = value.split("@")
if len(email) != 2:
return False
if self.is_hostname(email[1]):
if re.match("[a-zA-Z0-9][a-zA-Z0-9\-_+.]{0,200}$", email[0]):
return True
else:
return False
else:
return False
@classmethod
def is_phone(self, value):
if re.match("((^0)|([+(^00)][1-9][0-9]{1,2}))([ \-()]{0,2}[0-9]){6,11}$", value):
return True
else:
return False
@classmethod
def is_hostname(self, value):
if re.match("([a-zA-z0-9][a-zA-z0-9-]{0,61}[a-zA-z0-9]\.)*[a-zA-z0-9][a-zA-z0-9-]{0,61}[a-zA-z0-9]\.[a-zA-z]{2,3}(\.[a-zA-z]{2})?$", value):
return True
else:
return False
@classmethod
def is_ip_address(self, value):
ips = value.split(".")
if len(ips) != 4:
return False
else:
for ip in ips:
if not re.match("(1?[0-9]?[0-9]$)|(2[0-4][0-9]$)|(25[0-5]$)", ip):
return False
return True
@classmethod
def is_number(self, value):
if re.match("-?(0|[1-9][0-9]*)(\.[0-9]*)?$", value):
return True
else:
return False
@classmethod
def is_integer(self, value):
if re.match("-?(0|[1-9][0-9]*)$", value):
return True
else:
return False
@classmethod
def is_date(self, value):
if re.match("[0-9]{4}-(0[1-9]|1[0-2])-([0-2][0-9]|3[0-1])$", value):
return True
else:
return False
@classmethod
def is_time(self, value):
if re.match("([01][0-9]|2[0-3]):([0-5][0-9]|60):([0-5][0-9]|60)$", value):
return True
else:
return False
@classmethod
def is_datetime(self, value):
if re.match("[0-9]{4}-(0[0-9]|1[0-2])-([0-2][0-9]|3[0-1])[ T]([01][0-9]|2[0-3]):([0-5][0-9]|60):([0-5][0-9]|60)$", value):
return True
else:
return False
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
self._EMAIL_REGULAR_EXPRESSION = "[a-zA-Z0-9][a-zA-Z0-9\-_+.]{0,200}@([a-zA-z0-9][a-zA-z0-9-]{0,61}[a-zA-z0-9]\.)*[a-zA-z0-9][a-zA-z0-9-]{0,61}[a-zA-z0-9]\.[a-zA-z]{2,3}(\.[a-zA-z]{2})?"
def _preserve_hostname(self, email):
filtered = email.group().split("@")
filtered[0] = "[FILTERED]"
return '@'.join(filtered)
def _preserve_phone_country_code(self, phone):
filtered = str(phone.group())
# how are we supposed to tell the numbers in the code apart from the numbers in the phone?!
# for example, +359123456789 could be:
# country code +359 123456789 or +35 9123456789 or even +3 59123456789
# assuming that the country code is always three digits
if filtered[0] == '+' or (filtered[0] == '0' and filtered[1] == '0'):
if filtered[0] == '+':
filtered = filtered[0] + filtered[1] + filtered[2] + filtered[3] + " [FILTERED]"
else:
filtered = filtered[0] + filtered[1] + filtered[2] + filtered[3] + filtered[4] + filtered[5]
filtered += " FILTERED"
else:
filtered = "[FILTERED]"
return filtered
def _preserve_email_username(self, email):
filtered = email.group().split("@")
if len(filtered[0]) <= 6:
filtered[0] = "[FILTERED]"
else:
filtered[0] = filtered[0][0] + filtered[0][1] + filtered[0][2] + "[FILTERED]"
return '@'.join(filtered)
def filtered(self):
filtered_text = self._text
if self.partially_preserve_email_username:
filtered_text = re.sub(self._EMAIL_REGULAR_EXPRESSION, self._preserve_email_username, filtered_text)
elif self.preserve_email_hostname:
filtered_text = re.sub(self._EMAIL_REGULAR_EXPRESSION, self._preserve_hostname, filtered_text)
else:
filtered_text = re.sub(self._EMAIL_REGULAR_EXPRESSION, "[EMAIL]", filtered_text)
if self.preserve_phone_country_code:
filtered_text = re.sub("(0|([+(^00)][1-9][0-9]{1,2}))([ \-()]{0,2}[0-9]){6,11}", self._preserve_phone_country_code, filtered_text)
else:
filtered_text = re.sub("(0|([+(^00)][1-9][0-9]{1,2}))([ \-()]{0,2}[0-9]){6,11}", "[PHONE]", filtered_text)
return filtered_text

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

...FFF.F..F.....F..F..FF..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-ehz61c/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-ehz61c/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-ehz61c/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_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-ehz61c/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_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-ehz61c/test.py", line 100, in test_separates_preserved_country_code_from_filtered_phone_with_a_space
    self.assertEqual(filtered, filter.filtered())
AssertionError: 'Phone: +25 [FILTERED]' != 'Phone: +25( [FILTERED]'
- Phone: +25 [FILTERED]
+ Phone: +25( [FILTERED]
?           +


======================================================================
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-ehz61c/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-ehz61c/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-ehz61c/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-ehz61c/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-ehz61c/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-ehz61c/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-ehz61c/test.py", line 281, in test_validates_datetime_values
    self.assertFalse(solution.Validations.is_datetime('2012-00-19T23: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-ehz61c/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

----------------------------------------------------------------------
Ran 39 tests in 0.058s

FAILED (failures=13)

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

Елена обнови решението на 22.04.2014 14:58 (преди над 10 години)

+import re
+
+
+class Validations:
+ @classmethod
+ def is_email(self, value):
+ email = value.split("@")
+ if len(email) != 2:
+ return False
+ if self.is_hostname(email[1]):
+ if re.match("[a-zA-Z0-9][a-zA-Z0-9\-_+.]{0,200}$", email[0]):
+ return True
+ else:
+ return False
+ else:
+ return False
+
+ @classmethod
+ def is_phone(self, value):
+ if re.match("((^0)|([+(^00)][1-9][0-9]{1,2}))([ \-()]{0,2}[0-9]){6,11}$", value):
+ return True
+ else:
+ return False
+
+ @classmethod
+ def is_hostname(self, value):
+ if re.match("([a-zA-z0-9][a-zA-z0-9-]{0,61}[a-zA-z0-9]\.)*[a-zA-z0-9][a-zA-z0-9-]{0,61}[a-zA-z0-9]\.[a-zA-z]{2,3}(\.[a-zA-z]{2})?$", value):
+ return True
+ else:
+ return False
+
+ @classmethod
+ def is_ip_address(self, value):
+ ips = value.split(".")
+ if len(ips) != 4:
+ return False
+ else:
+ for ip in ips:
+ if not re.match("(1?[0-9]?[0-9]$)|(2[0-4][0-9]$)|(25[0-5]$)", ip):
+ return False
+ return True
+
+ @classmethod
+ def is_number(self, value):
+ if re.match("-?(0|[1-9][0-9]*)(\.[0-9]*)?$", value):
+ return True
+ else:
+ return False
+
+ @classmethod
+ def is_integer(self, value):
+ if re.match("-?(0|[1-9][0-9]*)$", value):
+ return True
+ else:
+ return False
+
+ @classmethod
+ def is_date(self, value):
+ if re.match("[0-9]{4}-(0[1-9]|1[0-2])-([0-2][0-9]|3[0-1])$", value):
+ return True
+ else:
+ return False
+
+ @classmethod
+ def is_time(self, value):
+ if re.match("([01][0-9]|2[0-3]):([0-5][0-9]|60):([0-5][0-9]|60)$", value):
+ return True
+ else:
+ return False
+
+ @classmethod
+ def is_datetime(self, value):
+ if re.match("[0-9]{4}-(0[0-9]|1[0-2])-([0-2][0-9]|3[0-1])[ T]([01][0-9]|2[0-3]):([0-5][0-9]|60):([0-5][0-9]|60)$", value):
+ return True
+ else:
+ return False
+
+
+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
+ self._EMAIL_REGULAR_EXPRESSION = "[a-zA-Z0-9][a-zA-Z0-9\-_+.]{0,200}@([a-zA-z0-9][a-zA-z0-9-]{0,61}[a-zA-z0-9]\.)*[a-zA-z0-9][a-zA-z0-9-]{0,61}[a-zA-z0-9]\.[a-zA-z]{2,3}(\.[a-zA-z]{2})?"
+
+ def _preserve_hostname(self, email):
+ filtered = email.group().split("@")
+ filtered[0] = "[FILTERED]"
+ return '@'.join(filtered)
+
+ def _preserve_phone_country_code(self, phone):
+ filtered = str(phone.group())
+ # how are we supposed to tell the numbers in the code apart from the numbers in the phone?!
+ # for example, +359123456789 could be:
+ # country code +359 123456789 or +35 9123456789 or even +3 59123456789
+ # assuming that the country code is always three digits
+ if filtered[0] == '+' or (filtered[0] == '0' and filtered[1] == '0'):
+ if filtered[0] == '+':
+ filtered = filtered[0] + filtered[1] + filtered[2] + filtered[3] + " [FILTERED]"
+ else:
+ filtered = filtered[0] + filtered[1] + filtered[2] + filtered[3] + filtered[4] + filtered[5]
+ filtered += " FILTERED"
+ else:
+ filtered = "[FILTERED]"
+ return filtered
+
+ def _preserve_email_username(self, email):
+ filtered = email.group().split("@")
+ if len(filtered[0]) <= 6:
+ filtered[0] = "[FILTERED]"
+ else:
+ filtered[0] = filtered[0][0] + filtered[0][1] + filtered[0][2] + "[FILTERED]"
+ return '@'.join(filtered)
+
+ def filtered(self):
+ filtered_text = self._text
+ if self.partially_preserve_email_username:
+ filtered_text = re.sub(self._EMAIL_REGULAR_EXPRESSION, self._preserve_email_username, filtered_text)
+ elif self.preserve_email_hostname:
+ filtered_text = re.sub(self._EMAIL_REGULAR_EXPRESSION, self._preserve_hostname, filtered_text)
+ else:
+ filtered_text = re.sub(self._EMAIL_REGULAR_EXPRESSION, "[EMAIL]", filtered_text)
+ if self.preserve_phone_country_code:
+ filtered_text = re.sub("(0|([+(^00)][1-9][0-9]{1,2}))([ \-()]{0,2}[0-9]){6,11}", self._preserve_phone_country_code, filtered_text)
+ else:
+ filtered_text = re.sub("(0|([+(^00)][1-9][0-9]{1,2}))([ \-()]{0,2}[0-9]){6,11}", "[PHONE]", filtered_text)
+ return filtered_text