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

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

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

Резултати

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

Код

import re
def is_match(regex, text):
return bool(re.match(regex, str(text)))
class Validations:
@classmethod
def is_integer(self, value): # => True or False
expr = "^-?(0|[1-9]\d*)$"
return is_match(expr, value)
@classmethod
def is_number(self, value): # => True or False
expr = "^-?(0|([1-9]\d*))(\\.\d+)?$"
return is_match(expr, value)
@classmethod
def is_date(self, value): # => True or False
expr = "^\d{4}-((0[1-9])|10|11|12)-((0[1-9])|(1\d)|(2\d)|(3[0-1]))$"
return is_match(expr, value)
@classmethod
def is_time(self, value): # => True or False
expr = "^([0-1]\d|2[0-3]):([0-5]\d):([0-5]\d)$"
return is_match(expr, value)
@classmethod
def is_datetime(self, value): # => True or False
if len(value) < 12:
return False
if value[10] == ' ' or value[10] == 'T':
return self.is_date(value[0:10]) and self.is_time(value[11:])
return False
@classmethod
def is_ip_address(self, value): # => True or False
reg = "(\d|([1-9]\d)|(1\d\d)|(2[0-4]\d)|(25[0-5]))"
address = "^(" + reg + ".){3}" + reg + "$"
return is_match(address, value)
@classmethod
def is_phone(self, value): # => True or False
prefix = "(\s|\(|\)|-){,2}"
internal = "(" + prefix + "\d){6,11}"
local = "^0[^0]" + internal + "$"
international = "^(00|\+)[1-9][0-9]{,2}" + internal + "$"
return is_match(international, value) or is_match(local, value)
@classmethod
def is_hostname(self, value): # => True or False
tld = "[a-zA-z]{2,3}(.([a-zA-Z]){2,3})?"
domain_st = "[0-9a-zA-Z]"
domain_nodash = domain_st + "{,62}"
domain_dash = "((" + domain_st + "|\-){,61}" + domain_st + ")"
domain = "(" + domain_st + \
"(" + domain_nodash + "|" + domain_dash + ")"")"
hostname = "^(" + domain + "\.){1,}" + tld + "$"
return is_match(hostname, value)
@classmethod
def is_email(self, value): # => True or False
mail = value.split("@")
if len(mail) != 2:
return False
# 200 други букви, цифри, долни черти, плюсове, точки или тирета
mail_name = "^[0-9a-zA-Z]([a-zA-Z0-9]|\_|\+|\.|\-){,200}$"
return is_match(mail_name, mail[0]) and self.is_hostname(mail[1])
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):
return self.__filter_phone_text(self.__filter_email_text(self.text))
def __filter_email_text(self, text):
if text != "":
for start in range(0, len(text)):
for end in reversed(range(start, len(text) + 1)):
if Validations.is_email(text[start:end]) == True:
return text[:start] + self.__filter_email(text[start:end]) + self.__filter_email_text(text[end:])
return text
def __filter_email(self, text):
filtered = ""
sword = "[FILTERED]"
mail = text.split("@")
if self.partially_preserve_email_username == True:
if len(mail[0]) >= 6:
filtered += mail[0][:3]
filtered += sword
return filtered + "@" + mail[1]
if self.preserve_email_hostname == True:
return sword + "@" + mail[1]
return "[EMAIL]"
def __filter_phone_text(self, text):
if text != "":
for start in range(0, len(text)):
for end in reversed(range(start, len(text) + 1)):
if Validations.is_phone(text[start:end]) == True:
return text[:start] + self.__filter_phone(text[start:end]) + self.__filter_phone_text(text[end:])
return text
def __get_phone_code(text):
x = re.findall("^((00|\+)[1-9][0-9]{,2})", text)
if bool(x) == True:
return x[0][0]
return ""
def __filter_phone(self, text):
if self.preserve_phone_country_code == True:
return PrivacyFilter.__get_phone_code(text) + " " + "[FILTERED]"
return "[PHONE]"

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

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


======================================================================
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-1on81th/test.py", line 37, in test_obfuscates_more_complicated_emails
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: 'Contact: [EMAIL],[EMAIL]' != 'Contact: [EMAIL][EMAIL]'
- Contact: [EMAIL],[EMAIL]
?                 -
+ Contact: [EMAIL][EMAIL]


======================================================================
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-1on81th/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-1on81th/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-1on81th/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-1on81th/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.311s

FAILED (failures=7)

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

Марио обнови решението на 22.04.2014 17:36 (преди около 10 години)

+import re
+
+
+def is_match(regex, text):
+ return bool(re.match(regex, str(text)))
+
+
+class Validations:
+
+ @classmethod
+ def is_integer(self, value): # => True or False
+ expr = "^-?(0|[1-9]\d*)$"
+ return is_match(expr, value)
+
+ @classmethod
+ def is_number(self, value): # => True or False
+ expr = "^-?(0|([1-9]\d*))(\\.\d+)?$"
+ return is_match(expr, value)
+
+ @classmethod
+ def is_date(self, value): # => True or False
+ expr = "^\d{4}-((0[1-9])|10|11|12)-((0[1-9])|(1\d)|(2\d)|(3[0-1]))$"
+ return is_match(expr, value)
+
+ @classmethod
+ def is_time(self, value): # => True or False
+ expr = "^([0-1]\d|2[0-3]):([0-5]\d):([0-5]\d)$"
+ return is_match(expr, value)
+
+ @classmethod
+ def is_datetime(self, value): # => True or False
+ if len(value) < 12:
+ return False
+ if value[10] == ' ' or value[10] == 'T':
+ return self.is_date(value[0:10]) and self.is_time(value[11:])
+ return False
+
+ @classmethod
+ def is_ip_address(self, value): # => True or False
+ reg = "(\d|([1-9]\d)|(1\d\d)|(2[0-4]\d)|(25[0-5]))"
+ address = "^(" + reg + ".){3}" + reg + "$"
+ return is_match(address, value)
+
+ @classmethod
+ def is_phone(self, value): # => True or False
+ prefix = "(\s|\(|\)|-){,2}"
+ internal = "(" + prefix + "\d){6,11}"
+ local = "^0[^0]" + internal + "$"
+ international = "^(00|\+)[1-9][0-9]{,2}" + internal + "$"
+ return is_match(international, value) or is_match(local, value)
+
+ @classmethod
+ def is_hostname(self, value): # => True or False
+ tld = "[a-zA-z]{2,3}(.([a-zA-Z]){2,3})?"
+ domain_st = "[0-9a-zA-Z]"
+ domain_nodash = domain_st + "{,62}"
+ domain_dash = "((" + domain_st + "|\-){,61}" + domain_st + ")"
+ domain = "(" + domain_st + \
+ "(" + domain_nodash + "|" + domain_dash + ")"")"
+ hostname = "^(" + domain + "\.){1,}" + tld + "$"
+ return is_match(hostname, value)
+
+ @classmethod
+ def is_email(self, value): # => True or False
+ mail = value.split("@")
+ if len(mail) != 2:
+ return False
+ # 200 други букви, цифри, долни черти, плюсове, точки или тирета
+ mail_name = "^[0-9a-zA-Z]([a-zA-Z0-9]|\_|\+|\.|\-){,200}$"
+ return is_match(mail_name, mail[0]) and self.is_hostname(mail[1])
+
+
+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):
+ return self.__filter_phone_text(self.__filter_email_text(self.text))
+
+ def __filter_email_text(self, text):
+ if text != "":
+ for start in range(0, len(text)):
+ for end in reversed(range(start, len(text) + 1)):
+ if Validations.is_email(text[start:end]) == True:
+ return text[:start] + self.__filter_email(text[start:end]) + self.__filter_email_text(text[end:])
+ return text
+
+ def __filter_email(self, text):
+ filtered = ""
+ sword = "[FILTERED]"
+ mail = text.split("@")
+ if self.partially_preserve_email_username == True:
+ if len(mail[0]) >= 6:
+ filtered += mail[0][:3]
+ filtered += sword
+ return filtered + "@" + mail[1]
+ if self.preserve_email_hostname == True:
+ return sword + "@" + mail[1]
+ return "[EMAIL]"
+
+ def __filter_phone_text(self, text):
+ if text != "":
+ for start in range(0, len(text)):
+ for end in reversed(range(start, len(text) + 1)):
+ if Validations.is_phone(text[start:end]) == True:
+ return text[:start] + self.__filter_phone(text[start:end]) + self.__filter_phone_text(text[end:])
+ return text
+
+ def __get_phone_code(text):
+ x = re.findall("^((00|\+)[1-9][0-9]{,2})", text)
+ if bool(x) == True:
+ return x[0][0]
+ return ""
+
+ def __filter_phone(self, text):
+ if self.preserve_phone_country_code == True:
+ return PrivacyFilter.__get_phone_code(text) + " " + "[FILTERED]"
+ return "[PHONE]"