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

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

Към профила на Елица Илиева

Резултати

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

Код

import re
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):
if PrivacyFilter.partially_preserve_email_username:
self.text = self.text.replace(''.join(
[i.split('@', 1)[1] for i in text.split(' ')
if Validations.is_email(i)]), '[FILTERED]')
if PrivacyFilter.preserve_email_hostname:
self.text = self.text.replace(''.join(
[i.split('@', 1)[0] for i in text.split(' ')
if Validations.is_email(i)]), '[FILTERED]')
self.text = self.text.replace(''.join(
[i for i in text.split(' ') if Validations.is_email(i)]),
'[EMAIL]')
self.text = self.text.replace(''.join(
[i for i in text.split(' ') if Validations.is_phone(i)]),
'[PHONE]')
return self.text
class Validations():
@staticmethod
def is_email(value):
if len(value) <= 201:
return bool(re.match("^[^\W_][\w+-.]*@[\w+-.]+$",
str(value))) and Validations.is_hostname(
str(value).split('@')[1])
return False
@staticmethod
def is_phone(value):
if str(value).startswith('00') or str(value).startswith('+'):
return bool(re.match("^[\+|00]\d{1,3}[-]?[-( )]?(\d[-()]?)*\d$",
str(value)))
if str(value).startswith('0'):
return bool(re.match("^0[1-9]{1,3}-?[-( )]?(\d[-()]?)*\d$",
str(value)))
@staticmethod
def is_hostname(value):
#if str(value).rfind('.') != -1:
#a = bool(re.match(""), str(value))
return all(re.match("^[^\W_][A-Za-z0-9-]{0,63}(?!-)$",
subdomain) for subdomain in value.split('.'))
@staticmethod
def is_ip_address(value):
return bool(re.match(
"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}"
"([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$",
str(value)))
@staticmethod
def is_number(value):
return bool(re.match("^-?(0|[1-9][0-9]*)"
"|-?(0|[1-9][0-9]*)(.?[0-9]+)$",
str(value)))
@staticmethod
def is_integer(value):
return bool(re.match("^-?(0|[1-9][0-9]*)$",
str(value)))
@staticmethod
def is_time(value):
return bool(re.match("^([0-1][0-9]|2[0-3]):"
"([0-5][0-9]:)([0-5][0-9])$",
str(value)))
@staticmethod
def is_date(value):
return bool(re.match("^([0-9]){4}-"
"(0[1-9]|1[0-2])-(0[0-9]|[1-2][0-9]|3[0-1])$",
str(value)))
@staticmethod
def is_datetime(value):
return Validations.is_date(
re.split('T| ', str(value))[0]) and Validations.is_time(
re.split('T| ', str(value))[1])

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

EEEEEEEEEEEE.F.FF..F..FFFFFFF..FF..F...
======================================================================
ERROR: test_allows_email_hostname_to_be_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-1qusa2k/test.py", line 54, in test_allows_email_hostname_to_be_preserved
    self.assertEqual('[FILTERED]@example.com', self.filter_email_usernames('someone@example.com'))
  File "/tmp/d20140513-11348-1qusa2k/test.py", line 11, in filter_email_usernames
    return filter.filtered()
  File "/tmp/d20140513-11348-1qusa2k/solution.py", line 21, in filtered
    [i for i in text.split(' ') if Validations.is_email(i)]),
NameError: global name 'text' is not defined

======================================================================
ERROR: 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-1qusa2k/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'))
  File "/tmp/d20140513-11348-1qusa2k/test.py", line 16, in partially_filter_email_usernames
    return filter.filtered()
  File "/tmp/d20140513-11348-1qusa2k/solution.py", line 21, in filtered
    [i for i in text.split(' ') if Validations.is_email(i)]),
NameError: global name 'text' is not defined

======================================================================
ERROR: 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-1qusa2k/test.py", line 64, in test_does_not_brake_with_unicode
    self.assertEqual('За връзка: [FILTERED]@example.com', self.partially_filter_email_usernames('За връзка: me@example.com'))
  File "/tmp/d20140513-11348-1qusa2k/test.py", line 16, in partially_filter_email_usernames
    return filter.filtered()
  File "/tmp/d20140513-11348-1qusa2k/solution.py", line 21, in filtered
    [i for i in text.split(' ') if Validations.is_email(i)]),
NameError: global name 'text' is not defined

======================================================================
ERROR: 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-1qusa2k/test.py", line 48, in test_does_not_filter_invalid_emails
    self.assertEqual(text, solution.PrivacyFilter(text).filtered())
  File "/tmp/d20140513-11348-1qusa2k/solution.py", line 21, in filtered
    [i for i in text.split(' ') if Validations.is_email(i)]),
NameError: global name 'text' is not defined

======================================================================
ERROR: 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-1qusa2k/test.py", line 86, in test_does_not_filter_invalid_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
  File "/tmp/d20140513-11348-1qusa2k/solution.py", line 21, in filtered
    [i for i in text.split(' ') if Validations.is_email(i)]),
NameError: global name 'text' is not defined

======================================================================
ERROR: 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-1qusa2k/test.py", line 76, in test_filters_more_complex_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
  File "/tmp/d20140513-11348-1qusa2k/solution.py", line 21, in filtered
    [i for i in text.split(' ') if Validations.is_email(i)]),
NameError: global name 'text' is not defined

======================================================================
ERROR: 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-1qusa2k/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'))
  File "/tmp/d20140513-11348-1qusa2k/test.py", line 16, in partially_filter_email_usernames
    return filter.filtered()
  File "/tmp/d20140513-11348-1qusa2k/solution.py", line 21, in filtered
    [i for i in text.split(' ') if Validations.is_email(i)]),
NameError: global name 'text' is not defined

======================================================================
ERROR: 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-1qusa2k/test.py", line 37, in test_obfuscates_more_complicated_emails
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
  File "/tmp/d20140513-11348-1qusa2k/solution.py", line 21, in filtered
    [i for i in text.split(' ') if Validations.is_email(i)]),
NameError: global name 'text' is not defined

======================================================================
ERROR: test_obfuscates_simple_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-1qusa2k/test.py", line 24, in test_obfuscates_simple_emails
    self.assertEqual('Contact: [EMAIL]', solution.PrivacyFilter('Contact: someone@example.com').filtered())
  File "/tmp/d20140513-11348-1qusa2k/solution.py", line 21, in filtered
    [i for i in text.split(' ') if Validations.is_email(i)]),
NameError: global name 'text' is not defined

======================================================================
ERROR: 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-1qusa2k/test.py", line 89, in test_preserves_whitespace_around_phones
    self.assertEqual(' [PHONE] or...', solution.PrivacyFilter(' +359881212-12-1 2 or...').filtered())
  File "/tmp/d20140513-11348-1qusa2k/solution.py", line 21, in filtered
    [i for i in text.split(' ') if Validations.is_email(i)]),
NameError: global name 'text' is not defined

======================================================================
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-1qusa2k/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-1qusa2k/solution.py", line 21, in filtered
    [i for i in text.split(' ') if Validations.is_email(i)]),
NameError: global name 'text' is not defined

======================================================================
ERROR: test_works_with_blank_or_whitespace_strings_and_preserves_whitespace (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-1qusa2k/test.py", line 19, in test_works_with_blank_or_whitespace_strings_and_preserves_whitespace
    self.assertEqual('', solution.PrivacyFilter('').filtered())
  File "/tmp/d20140513-11348-1qusa2k/solution.py", line 21, in filtered
    [i for i in text.split(' ') if Validations.is_email(i)]),
NameError: global name 'text' is not defined

======================================================================
FAIL: test_allows_validation_for_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-1qusa2k/test.py", line 106, in test_allows_validation_for_emails
    self.assertFalse(solution.Validations.is_email('invalid@email'))
AssertionError: True is not false

======================================================================
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-1qusa2k/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-1qusa2k/test.py", line 160, in test_can_validate_more_complex_phone_numbers
    self.assertIs(solution.Validations.is_phone(phone), valid)
AssertionError: None 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-1qusa2k/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-1qusa2k/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-1qusa2k/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-1qusa2k/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-1qusa2k/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-1qusa2k/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-1qusa2k/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_returns_boolean_True_or_False (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-1qusa2k/test.py", line 110, in test_returns_boolean_True_or_False
    self.assertIs(solution.Validations.is_email('invalid@email'), False)
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-1qusa2k/test.py", line 282, in test_validates_datetime_values
    self.assertFalse(solution.Validations.is_datetime('2012-01-00T23: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-1qusa2k/test.py", line 168, in test_validates_hostnames
    self.assertFalse(solution.Validations.is_hostname('localhost'))
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-1qusa2k/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.047s

FAILED (failures=14, errors=12)

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

Елица обнови решението на 23.04.2014 16:31 (преди над 10 години)

+import re
+
+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):
+ self.text = self.text.replace(''.join([i for i in text.split(' ') if Validations.is_email(i)]), '[EMAIL]')
+ self.text = self.text.replace(''.join([i for i in text.split(' ') if Validations.is_phone(i)]), '[PHONE]')
+ return self.text
+
+
+class Validations():
+ @staticmethod
+ def is_email(value):
+ if len(value) <= 201:
+ return bool(re.match("^[^\W_][\w+-.]*@[\w+-.]+$",
+ str(value))) and Validations.is_hostname(
+ str(value).split('@')[1])
+ return False
+
+ @staticmethod
+ def is_phone(value):
+ if str(value).startswith('00') or str(value).startswith('+'):
+ return bool(re.match("^[\+|00]\d{1,3}[-]?[-( )]?(\d[-()]?)*\d$",
+ str(value)))
+ if str(value).startswith('0'):
+ return bool(re.match("^0[1-9]{1,3}-?[-( )]?(\d[-()]?)*\d$",
+ str(value)))
+
+ @staticmethod
+ def is_hostname(value):
+ #if str(value).rfind('.') != -1:
+ #a = bool(re.match(""), str(value))
+ return all(re.match("^[^\W_][A-Za-z0-9-]{0,63}(?!-)$",
+ subdomain) for subdomain in value.split('.'))
+
+ @staticmethod
+ def is_ip_address(value):
+ return bool(re.match(
+ "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}"
+ "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$",
+ str(value)))
+
+ @staticmethod
+ def is_number(value):
+ return bool(re.match("^-?(0|[1-9][0-9]*)"
+ "|-?(0|[1-9][0-9]*)(.?[0-9]+)$",
+ str(value)))
+
+ @staticmethod
+ def is_integer(value):
+ return bool(re.match("^-?(0|[1-9][0-9]*)$",
+ str(value)))
+
+ @staticmethod
+ def is_time(value):
+ return bool(re.match("^([0-1][0-9]|2[0-3]):"
+ "([0-5][0-9]:)([0-5][0-9])$",
+ str(value)))
+
+ @staticmethod
+ def is_date(value):
+ return bool(re.match("^([0-9]){4}-"
+ "(0[1-9]|1[0-2])-(0[0-9]|[1-2][0-9]|3[0-1])$",
+ str(value)))
+ @staticmethod
+ def is_datetime(value):
+ return Validations.is_date(
+ re.split('T| ', str(value))[0]) and Validations.is_time(
+ re.split('T| ', str(value))[1])

Елица обнови решението на 23.04.2014 16:55 (преди над 10 години)

import re
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):
- self.text = self.text.replace(''.join([i for i in text.split(' ') if Validations.is_email(i)]), '[EMAIL]')
- self.text = self.text.replace(''.join([i for i in text.split(' ') if Validations.is_phone(i)]), '[PHONE]')
+ if PrivacyFilter.partially_preserve_email_username:
+ self.text = self.text.replace(''.join(
+ [i.split('@', 1)[1] for i in text.split(' ')
+ if Validations.is_email(i)]), '[EMAIL]')
+ if PrivacyFilter.preserve_email_hostname:
+ self.text = self.text.replace(''.join(
+ [i.split('@', 1)[0] for i in text.split(' ')
+ if Validations.is_email(i)]), '[EMAIL]')
+ self.text = self.text.replace(''.join(
+ [i for i in text.split(' ') if Validations.is_email(i)]),
+ '[EMAIL]')
+ self.text = self.text.replace(''.join(
+ [i for i in text.split(' ') if Validations.is_phone(i)]),
+ '[PHONE]')
return self.text
class Validations():
@staticmethod
def is_email(value):
if len(value) <= 201:
return bool(re.match("^[^\W_][\w+-.]*@[\w+-.]+$",
str(value))) and Validations.is_hostname(
str(value).split('@')[1])
return False
@staticmethod
def is_phone(value):
if str(value).startswith('00') or str(value).startswith('+'):
return bool(re.match("^[\+|00]\d{1,3}[-]?[-( )]?(\d[-()]?)*\d$",
str(value)))
if str(value).startswith('0'):
return bool(re.match("^0[1-9]{1,3}-?[-( )]?(\d[-()]?)*\d$",
str(value)))
@staticmethod
def is_hostname(value):
#if str(value).rfind('.') != -1:
#a = bool(re.match(""), str(value))
return all(re.match("^[^\W_][A-Za-z0-9-]{0,63}(?!-)$",
subdomain) for subdomain in value.split('.'))
@staticmethod
def is_ip_address(value):
return bool(re.match(
"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}"
"([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$",
str(value)))
@staticmethod
def is_number(value):
return bool(re.match("^-?(0|[1-9][0-9]*)"
"|-?(0|[1-9][0-9]*)(.?[0-9]+)$",
str(value)))
@staticmethod
def is_integer(value):
return bool(re.match("^-?(0|[1-9][0-9]*)$",
str(value)))
@staticmethod
def is_time(value):
return bool(re.match("^([0-1][0-9]|2[0-3]):"
"([0-5][0-9]:)([0-5][0-9])$",
str(value)))
@staticmethod
def is_date(value):
return bool(re.match("^([0-9]){4}-"
"(0[1-9]|1[0-2])-(0[0-9]|[1-2][0-9]|3[0-1])$",
str(value)))
@staticmethod
def is_datetime(value):
return Validations.is_date(
re.split('T| ', str(value))[0]) and Validations.is_time(
re.split('T| ', str(value))[1])

Елица обнови решението на 23.04.2014 16:56 (преди над 10 години)

import re
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):
if PrivacyFilter.partially_preserve_email_username:
self.text = self.text.replace(''.join(
[i.split('@', 1)[1] for i in text.split(' ')
- if Validations.is_email(i)]), '[EMAIL]')
+ if Validations.is_email(i)]), '[FILTERED]')
if PrivacyFilter.preserve_email_hostname:
self.text = self.text.replace(''.join(
[i.split('@', 1)[0] for i in text.split(' ')
- if Validations.is_email(i)]), '[EMAIL]')
+ if Validations.is_email(i)]), '[FILTERED]')
self.text = self.text.replace(''.join(
[i for i in text.split(' ') if Validations.is_email(i)]),
'[EMAIL]')
self.text = self.text.replace(''.join(
[i for i in text.split(' ') if Validations.is_phone(i)]),
'[PHONE]')
return self.text
class Validations():
@staticmethod
def is_email(value):
if len(value) <= 201:
return bool(re.match("^[^\W_][\w+-.]*@[\w+-.]+$",
str(value))) and Validations.is_hostname(
str(value).split('@')[1])
return False
@staticmethod
def is_phone(value):
if str(value).startswith('00') or str(value).startswith('+'):
return bool(re.match("^[\+|00]\d{1,3}[-]?[-( )]?(\d[-()]?)*\d$",
str(value)))
if str(value).startswith('0'):
return bool(re.match("^0[1-9]{1,3}-?[-( )]?(\d[-()]?)*\d$",
str(value)))
@staticmethod
def is_hostname(value):
#if str(value).rfind('.') != -1:
#a = bool(re.match(""), str(value))
return all(re.match("^[^\W_][A-Za-z0-9-]{0,63}(?!-)$",
subdomain) for subdomain in value.split('.'))
@staticmethod
def is_ip_address(value):
return bool(re.match(
"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}"
"([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$",
str(value)))
@staticmethod
def is_number(value):
return bool(re.match("^-?(0|[1-9][0-9]*)"
"|-?(0|[1-9][0-9]*)(.?[0-9]+)$",
str(value)))
@staticmethod
def is_integer(value):
return bool(re.match("^-?(0|[1-9][0-9]*)$",
str(value)))
@staticmethod
def is_time(value):
return bool(re.match("^([0-1][0-9]|2[0-3]):"
"([0-5][0-9]:)([0-5][0-9])$",
str(value)))
@staticmethod
def is_date(value):
return bool(re.match("^([0-9]){4}-"
"(0[1-9]|1[0-2])-(0[0-9]|[1-2][0-9]|3[0-1])$",
str(value)))
@staticmethod
def is_datetime(value):
return Validations.is_date(
re.split('T| ', str(value))[0]) and Validations.is_time(
re.split('T| ', str(value))[1])