Решение на Регулярни изрази от Тихомир Янев

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

Към профила на Тихомир Янев

Резултати

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

Код

import re
class PrivacyFilter:
def __init__(self, string):
self.string, self.partially_preserve_email_username = string, False
self.preserve_phone_country_code = self.preserve_email_hostname = False
def filtered(self):
output = self.string
for x in re.findall('{}@{}'.format(
Validations.REGEX['email'], Validations.REGEX[
'host']), self.string):
output = re.sub(re.escape(x), self.filter_email(
x), output)
for x in re.findall(
Validations.REGEX['phone'], self.string):
output = re.sub(re.escape(x), self.filter_phone(x), output)
return output
def filter_phone(self, string):
return string[0:4] + ' [FILTERED]' \
if self.preserve_phone_country_code and \
string.startswith('+') else '[PHONE]'
def filter_email(self, string):
email, host = string.split('@')
if self.partially_preserve_email_username:
pos = 0 if len(email) < 6 else 3
elif self.preserve_email_hostname:
pos = 0
else:
return '[EMAIL]'
return '{}[FILTERED]@{}'.format(email[0:pos], host)
class Validations:
REGEX = {
'email': '[a-z0-9][a-z0-9_\+\.-]{0,200}',
'number': '-?[0-9]+(?:\.[0-9])?[0-9]*',
'date': '[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[01])',
'time': '(?:[01][0-9]|2[0-3]):{0}:{0}$'.format('[0-5][0-9]'),
'phone': '(?:(?:0[1-9]|\+)|(?:00|\+[1-9][0-9]{0,2}))'
'(?:[ -()]{0,2}[0-9]){6,11}',
'host': '(?:{0})*?{0}{1}(?:\.{1})?'.format(
'[a-z0-9][a-z0-9-]{0,61}[a-z0-9]\.', '[a-z]{2,3}'),
'number': '-?[0-9]+(?:\.[0-9])?[0-9]*'
}
@staticmethod
def start_end_re(regex):
return '^{}$'.format(regex)
@classmethod
def is_email(cls, string):
if string.count('@') != 1: return False
email, host = string.split('@')
return re.match(cls.start_end_re(
cls.REGEX['email']), email, re.I) and cls.is_hostname(host)
@classmethod
def is_hostname(cls, string):
return re.match(cls.start_end_re(cls.REGEX['host']), string, re.I)
@classmethod
def is_ip_address(cls, string):
if string.count('.') != 3: return False
return all(int(x) in range(256) for x in string.split('.'))
@classmethod
def is_number(cls, string):
return re.match(cls.start_end_re(cls.REGEX['number']), string)
@classmethod
def is_integer(cls, string):
return string.count('.') == 0 and cls.is_number(string)
@classmethod
def is_date(cls, string):
return re.match(cls.start_end_re(cls.REGEX['date']), string)
@classmethod
def is_time(cls, string):
return re.match(cls.start_end_re(cls.REGEX['time']), string)
@classmethod
def is_datetime(cls, string):
if len(string) != 19: return False
return cls.is_date(string[0:10]) and cls.is_time(string[-8:])
@classmethod
def is_phone(cls, string):
return re.match(cls.start_end_re(cls.REGEX['phone']), string)

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

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


======================================================================
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-1er5j21/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_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-1er5j21/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...' != ' [PHONE]-12-1 2 or...'
-  [PHONE] or...
+  [PHONE]-12-1 2 or...
?         +++++++


======================================================================
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-1er5j21/test.py", line 100, in test_separates_preserved_country_code_from_filtered_phone_with_a_space
    self.assertEqual(filtered, filter.filtered())
AssertionError: 'Phone: 0025 [FILTERED]' != 'Phone: [PHONE]'
- Phone: 0025 [FILTERED]
+ Phone: [PHONE]


======================================================================
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-1er5j21/test.py", line 124, in test_can_validate_more_complex_emails
    self.assertIs(solution.Validations.is_email(email), valid)
AssertionError: <_sre.SRE_Match object at 0xb7750330> is not True

======================================================================
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-1er5j21/test.py", line 160, in test_can_validate_more_complex_phone_numbers
    self.assertIs(solution.Validations.is_phone(phone), valid)
AssertionError: <_sre.SRE_Match object at 0xb7750410> is not True

======================================================================
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-1er5j21/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-1er5j21/test.py", line 179, in test_handles_multiline_strings_in_hostname_validation_properly
    self.assertFalse(solution.Validations.is_hostname("foo.com\n"))
AssertionError: <_sre.SRE_Match object at 0xb7750480> 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-1er5j21/test.py", line 259, in test_handles_newlines_in_date_validation
    self.assertFalse(solution.Validations.is_date("2012-11-19\n"))
AssertionError: <_sre.SRE_Match object at 0xb77504b8> 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-1er5j21/test.py", line 288, in test_handles_newlines_in_time_and_datetime_validation
    self.assertFalse(solution.Validations.is_time("12:01:01\n"))
AssertionError: <_sre.SRE_Match object at 0xb77504f0> 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-1er5j21/test.py", line 109, in test_returns_boolean_True_or_False
    self.assertIs(solution.Validations.is_email('foo@bar.com'), True)
AssertionError: <_sre.SRE_Match object at 0xb7750560> is not True

======================================================================
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-1er5j21/test.py", line 169, in test_validates_hostnames
    self.assertTrue(solution.Validations.is_hostname('1.2.3.4.xip.io'))
AssertionError: None 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-1er5j21/test.py", line 225, in test_validates_more_complex_integers
    self.assertFalse(solution.Validations.is_integer('00'))
AssertionError: <_sre.SRE_Match object at 0xb7750528> 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-1er5j21/test.py", line 205, in test_validates_more_complex_numbers
    self.assertFalse(solution.Validations.is_number('00'))
AssertionError: <_sre.SRE_Match object at 0xb77505d0> is not false

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

FAILED (failures=16)

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

Тихомир обнови решението на 17.04.2014 09:24 (преди около 10 години)

+import re
+
+class PrivacyFilter:
+ def __init__(self, string):
+ self.string = string
+ self.preserve_phone_country_code = self.preserve_email_hostname \
+ = self.partially_preserve_email_username = False
+
+ def filtered(self):
+ output = self.string
+
+ for x in re.findall('{}@{}'.format(
+ Validations.PATTERNS['email'], Validations.PATTERNS[
+ 'host']), self.string):
+ output = re.sub(re.escape(x), self.filter_email(
+ x), output)
+
+ for x in re.findall(
+ Validations.PATTERNS['phone'], self.string):
+ output = re.sub(re.escape(x), self.filter_phone(x), output)
+
+ return output
+
+ def filter_phone(self, string):
+ return string[0:4] + ' [FILTERED]' \
+ if self.preserve_phone_country_code and \
+ string.startswith('+') else '[PHONE]'
+
+ def filter_email(self, string):
+ email, host = string.split('@')
+ if self.partially_preserve_email_username:
+ pos = 0 if len(email) < 6 else 3
+ elif self.preserve_email_hostname:
+ pos = 0
+ else:
+ return '[EMAIL]'
+
+ return '{}[FILTERED]@{}'.format(email[0:pos], host)
+
+
+class Validations:
+ PATTERNS = {
+ 'email': '[a-z0-9][a-z0-9_\+\.-]{0,200}',
+ 'number': '-?[0-9]+(?:\.[0-9])?[0-9]*',
+ 'date': '[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[01])',
+ 'time': '(?:[01][0-9]|2[0-3]):{0}:{0}$'.format('[0-5][0-9]'),
+ 'phone': '(?:(?:0[1-9]|\+)|(?:00|\+[1-9][0-9]{0,2}))'
+ '(?:[ -()]{0,2}[0-9]){6,11}',
+ 'host': '(?:{0})*?{0}{1}(?:\.{1})?'.format(
+ '[a-z0-9][a-z0-9-]{0,61}[a-z0-9]\.', '[a-z]{2,3}'),
+ 'number': '-?[0-9]+(?:\.[0-9])?[0-9]*'
+ }
+
+ @classmethod
+ def start_end_re(cls, regex):
+ return '^{}$'.format(regex)
+
+ @classmethod
+ def is_email(cls, string):
+ if string.count('@') != 1:
+ return False
+ email, host = string.split('@')
+ return re.match(cls.start_end_re(
+ cls.PATTERNS['email']), email, re.I) and cls.is_hostname(host)
+
+ @classmethod
+ def is_hostname(cls, string):
+ return re.match(
+ cls.start_end_re(cls.PATTERNS['host']), string, re.I)
+
+ @classmethod
+ def is_ip_address(cls, string):
+ return len([x for x in string.split('.') \
+ if int(x) in range(0, 256)]) == 4
+
+ @classmethod
+ def is_number(cls, string):
+ return re.match(cls.start_end_re(
+ cls.PATTERNS['number']), string)
+
+ @classmethod
+ def is_integer(cls, string):
+ return string.count('.') == 0 and cls.is_number(string)
+
+ @classmethod
+ def is_date(cls, string):
+ return re.match(cls.start_end_re(
+ cls.PATTERNS['date']), string)
+
+ @classmethod
+ def is_time(cls, string):
+ return re.match(cls.start_end_re(
+ cls.PATTERNS['time']), string)
+
+ @classmethod
+ def is_datetime(cls, string):
+ if len(string) != 19: return False
+ return cls.is_date(string[0:10]) and cls.is_time(string[-8:])
+
+ @classmethod
+ def is_phone(cls, string):
+ return re.match(cls.start_end_re(
+ cls.PATTERNS['phone']), string)

Тихомир обнови решението на 17.04.2014 09:29 (преди около 10 години)

import re
class PrivacyFilter:
def __init__(self, string):
self.string = string
self.preserve_phone_country_code = self.preserve_email_hostname \
= self.partially_preserve_email_username = False
def filtered(self):
output = self.string
for x in re.findall('{}@{}'.format(
Validations.PATTERNS['email'], Validations.PATTERNS[
'host']), self.string):
output = re.sub(re.escape(x), self.filter_email(
x), output)
for x in re.findall(
Validations.PATTERNS['phone'], self.string):
output = re.sub(re.escape(x), self.filter_phone(x), output)
return output
def filter_phone(self, string):
return string[0:4] + ' [FILTERED]' \
if self.preserve_phone_country_code and \
string.startswith('+') else '[PHONE]'
def filter_email(self, string):
email, host = string.split('@')
if self.partially_preserve_email_username:
pos = 0 if len(email) < 6 else 3
elif self.preserve_email_hostname:
pos = 0
else:
return '[EMAIL]'
return '{}[FILTERED]@{}'.format(email[0:pos], host)
class Validations:
PATTERNS = {
'email': '[a-z0-9][a-z0-9_\+\.-]{0,200}',
'number': '-?[0-9]+(?:\.[0-9])?[0-9]*',
'date': '[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[01])',
'time': '(?:[01][0-9]|2[0-3]):{0}:{0}$'.format('[0-5][0-9]'),
'phone': '(?:(?:0[1-9]|\+)|(?:00|\+[1-9][0-9]{0,2}))'
'(?:[ -()]{0,2}[0-9]){6,11}',
'host': '(?:{0})*?{0}{1}(?:\.{1})?'.format(
'[a-z0-9][a-z0-9-]{0,61}[a-z0-9]\.', '[a-z]{2,3}'),
'number': '-?[0-9]+(?:\.[0-9])?[0-9]*'
}
- @classmethod
- def start_end_re(cls, regex):
+ @staticmethod
+ def start_end_re(regex):
return '^{}$'.format(regex)
@classmethod
def is_email(cls, string):
if string.count('@') != 1:
return False
email, host = string.split('@')
return re.match(cls.start_end_re(
cls.PATTERNS['email']), email, re.I) and cls.is_hostname(host)
@classmethod
def is_hostname(cls, string):
return re.match(
cls.start_end_re(cls.PATTERNS['host']), string, re.I)
@classmethod
def is_ip_address(cls, string):
return len([x for x in string.split('.') \
if int(x) in range(0, 256)]) == 4
@classmethod
def is_number(cls, string):
return re.match(cls.start_end_re(
cls.PATTERNS['number']), string)
@classmethod
def is_integer(cls, string):
return string.count('.') == 0 and cls.is_number(string)
@classmethod
def is_date(cls, string):
return re.match(cls.start_end_re(
cls.PATTERNS['date']), string)
@classmethod
def is_time(cls, string):
return re.match(cls.start_end_re(
cls.PATTERNS['time']), string)
@classmethod
def is_datetime(cls, string):
if len(string) != 19: return False
return cls.is_date(string[0:10]) and cls.is_time(string[-8:])
@classmethod
def is_phone(cls, string):
return re.match(cls.start_end_re(
cls.PATTERNS['phone']), string)

Тихомир обнови решението на 17.04.2014 23:28 (преди около 10 години)

import re
class PrivacyFilter:
def __init__(self, string):
self.string = string
self.preserve_phone_country_code = self.preserve_email_hostname \
= self.partially_preserve_email_username = False
def filtered(self):
output = self.string
for x in re.findall('{}@{}'.format(
- Validations.PATTERNS['email'], Validations.PATTERNS[
+ Validations.REGEX['email'], Validations.REGEX[
'host']), self.string):
output = re.sub(re.escape(x), self.filter_email(
x), output)
for x in re.findall(
- Validations.PATTERNS['phone'], self.string):
+ Validations.REGEX['phone'], self.string):
output = re.sub(re.escape(x), self.filter_phone(x), output)
return output
def filter_phone(self, string):
return string[0:4] + ' [FILTERED]' \
if self.preserve_phone_country_code and \
string.startswith('+') else '[PHONE]'
def filter_email(self, string):
email, host = string.split('@')
if self.partially_preserve_email_username:
pos = 0 if len(email) < 6 else 3
elif self.preserve_email_hostname:
pos = 0
else:
return '[EMAIL]'
return '{}[FILTERED]@{}'.format(email[0:pos], host)
class Validations:
- PATTERNS = {
+ REGEX = {
'email': '[a-z0-9][a-z0-9_\+\.-]{0,200}',
'number': '-?[0-9]+(?:\.[0-9])?[0-9]*',
'date': '[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[01])',
'time': '(?:[01][0-9]|2[0-3]):{0}:{0}$'.format('[0-5][0-9]'),
'phone': '(?:(?:0[1-9]|\+)|(?:00|\+[1-9][0-9]{0,2}))'
'(?:[ -()]{0,2}[0-9]){6,11}',
'host': '(?:{0})*?{0}{1}(?:\.{1})?'.format(
'[a-z0-9][a-z0-9-]{0,61}[a-z0-9]\.', '[a-z]{2,3}'),
'number': '-?[0-9]+(?:\.[0-9])?[0-9]*'
}
@staticmethod
def start_end_re(regex):
return '^{}$'.format(regex)
@classmethod
def is_email(cls, string):
- if string.count('@') != 1:
- return False
+ if string.count('@') != 1: return False
email, host = string.split('@')
return re.match(cls.start_end_re(
- cls.PATTERNS['email']), email, re.I) and cls.is_hostname(host)
+ cls.REGEX['email']), email, re.I) and cls.is_hostname(host)
@classmethod
def is_hostname(cls, string):
return re.match(
- cls.start_end_re(cls.PATTERNS['host']), string, re.I)
+ cls.start_end_re(cls.REGEX['host']), string, re.I)
@classmethod
def is_ip_address(cls, string):
return len([x for x in string.split('.') \
if int(x) in range(0, 256)]) == 4
@classmethod
def is_number(cls, string):
return re.match(cls.start_end_re(
- cls.PATTERNS['number']), string)
+ cls.REGEX['number']), string)
@classmethod
def is_integer(cls, string):
return string.count('.') == 0 and cls.is_number(string)
@classmethod
def is_date(cls, string):
return re.match(cls.start_end_re(
- cls.PATTERNS['date']), string)
+ cls.REGEX['date']), string)
@classmethod
def is_time(cls, string):
return re.match(cls.start_end_re(
- cls.PATTERNS['time']), string)
+ cls.REGEX['time']), string)
@classmethod
def is_datetime(cls, string):
if len(string) != 19: return False
return cls.is_date(string[0:10]) and cls.is_time(string[-8:])
@classmethod
def is_phone(cls, string):
return re.match(cls.start_end_re(
- cls.PATTERNS['phone']), string)
+ cls.REGEX['phone']), string)

Тихомир обнови решението на 17.04.2014 23:32 (преди около 10 години)

import re
class PrivacyFilter:
def __init__(self, string):
self.string = string
self.preserve_phone_country_code = self.preserve_email_hostname \
= self.partially_preserve_email_username = False
def filtered(self):
output = self.string
-
for x in re.findall('{}@{}'.format(
Validations.REGEX['email'], Validations.REGEX[
'host']), self.string):
output = re.sub(re.escape(x), self.filter_email(
x), output)
-
for x in re.findall(
Validations.REGEX['phone'], self.string):
output = re.sub(re.escape(x), self.filter_phone(x), output)
-
return output
def filter_phone(self, string):
return string[0:4] + ' [FILTERED]' \
if self.preserve_phone_country_code and \
string.startswith('+') else '[PHONE]'
def filter_email(self, string):
email, host = string.split('@')
if self.partially_preserve_email_username:
pos = 0 if len(email) < 6 else 3
elif self.preserve_email_hostname:
pos = 0
- else:
- return '[EMAIL]'
-
+ else: return '[EMAIL]'
return '{}[FILTERED]@{}'.format(email[0:pos], host)
class Validations:
REGEX = {
'email': '[a-z0-9][a-z0-9_\+\.-]{0,200}',
'number': '-?[0-9]+(?:\.[0-9])?[0-9]*',
'date': '[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[01])',
'time': '(?:[01][0-9]|2[0-3]):{0}:{0}$'.format('[0-5][0-9]'),
'phone': '(?:(?:0[1-9]|\+)|(?:00|\+[1-9][0-9]{0,2}))'
'(?:[ -()]{0,2}[0-9]){6,11}',
'host': '(?:{0})*?{0}{1}(?:\.{1})?'.format(
'[a-z0-9][a-z0-9-]{0,61}[a-z0-9]\.', '[a-z]{2,3}'),
'number': '-?[0-9]+(?:\.[0-9])?[0-9]*'
}
@staticmethod
def start_end_re(regex):
return '^{}$'.format(regex)
@classmethod
def is_email(cls, string):
if string.count('@') != 1: return False
email, host = string.split('@')
return re.match(cls.start_end_re(
cls.REGEX['email']), email, re.I) and cls.is_hostname(host)
@classmethod
def is_hostname(cls, string):
return re.match(
cls.start_end_re(cls.REGEX['host']), string, re.I)
@classmethod
def is_ip_address(cls, string):
return len([x for x in string.split('.') \
if int(x) in range(0, 256)]) == 4
@classmethod
def is_number(cls, string):
return re.match(cls.start_end_re(
cls.REGEX['number']), string)
@classmethod
def is_integer(cls, string):
return string.count('.') == 0 and cls.is_number(string)
@classmethod
def is_date(cls, string):
return re.match(cls.start_end_re(
cls.REGEX['date']), string)
@classmethod
def is_time(cls, string):
return re.match(cls.start_end_re(
cls.REGEX['time']), string)
@classmethod
def is_datetime(cls, string):
if len(string) != 19: return False
return cls.is_date(string[0:10]) and cls.is_time(string[-8:])
@classmethod
def is_phone(cls, string):
return re.match(cls.start_end_re(
cls.REGEX['phone']), string)

Тихомир обнови решението на 17.04.2014 23:35 (преди около 10 години)

import re
class PrivacyFilter:
def __init__(self, string):
self.string = string
self.preserve_phone_country_code = self.preserve_email_hostname \
= self.partially_preserve_email_username = False
def filtered(self):
output = self.string
for x in re.findall('{}@{}'.format(
Validations.REGEX['email'], Validations.REGEX[
- 'host']), self.string):
- output = re.sub(re.escape(x), self.filter_email(
- x), output)
+ 'host']), self.string):
+ output = re.sub(re.escape(x), self.filter_email(
+ x), output)
for x in re.findall(
Validations.REGEX['phone'], self.string):
output = re.sub(re.escape(x), self.filter_phone(x), output)
return output
def filter_phone(self, string):
return string[0:4] + ' [FILTERED]' \
if self.preserve_phone_country_code and \
string.startswith('+') else '[PHONE]'
def filter_email(self, string):
email, host = string.split('@')
if self.partially_preserve_email_username:
pos = 0 if len(email) < 6 else 3
elif self.preserve_email_hostname:
pos = 0
else: return '[EMAIL]'
return '{}[FILTERED]@{}'.format(email[0:pos], host)
class Validations:
REGEX = {
'email': '[a-z0-9][a-z0-9_\+\.-]{0,200}',
'number': '-?[0-9]+(?:\.[0-9])?[0-9]*',
'date': '[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[01])',
'time': '(?:[01][0-9]|2[0-3]):{0}:{0}$'.format('[0-5][0-9]'),
'phone': '(?:(?:0[1-9]|\+)|(?:00|\+[1-9][0-9]{0,2}))'
'(?:[ -()]{0,2}[0-9]){6,11}',
'host': '(?:{0})*?{0}{1}(?:\.{1})?'.format(
'[a-z0-9][a-z0-9-]{0,61}[a-z0-9]\.', '[a-z]{2,3}'),
'number': '-?[0-9]+(?:\.[0-9])?[0-9]*'
}
@staticmethod
def start_end_re(regex):
return '^{}$'.format(regex)
@classmethod
def is_email(cls, string):
if string.count('@') != 1: return False
email, host = string.split('@')
return re.match(cls.start_end_re(
cls.REGEX['email']), email, re.I) and cls.is_hostname(host)
@classmethod
def is_hostname(cls, string):
return re.match(
cls.start_end_re(cls.REGEX['host']), string, re.I)
@classmethod
def is_ip_address(cls, string):
return len([x for x in string.split('.') \
if int(x) in range(0, 256)]) == 4
@classmethod
def is_number(cls, string):
return re.match(cls.start_end_re(
cls.REGEX['number']), string)
@classmethod
def is_integer(cls, string):
return string.count('.') == 0 and cls.is_number(string)
@classmethod
def is_date(cls, string):
return re.match(cls.start_end_re(
cls.REGEX['date']), string)
@classmethod
def is_time(cls, string):
return re.match(cls.start_end_re(
cls.REGEX['time']), string)
@classmethod
def is_datetime(cls, string):
if len(string) != 19: return False
return cls.is_date(string[0:10]) and cls.is_time(string[-8:])
@classmethod
def is_phone(cls, string):
return re.match(cls.start_end_re(
cls.REGEX['phone']), string)
  • Да, много е забавно, че в Python можем да правим така:
self.preserve_phone_country_code = self.preserve_email_hostname \
   = self.partially_preserve_email_username = False

Не го прави, когато редът ти стане твърде дълъг.

  • Оправи това: else: return '[EMAIL]'

  • Идеята на синтаксиса за едноредови if-ове е да бъдат... на един ред. Тука виждам два реда и абсолютна липса на логика това да бъде така:

return len([x for x in string.split('.') \
    if int(x) in range(0, 256)]) == 4
  • \b е твой приятел :)

Тихомир обнови решението на 21.04.2014 13:27 (преди около 10 години)

import re
class PrivacyFilter:
def __init__(self, string):
- self.string = string
- self.preserve_phone_country_code = self.preserve_email_hostname \
- = self.partially_preserve_email_username = False
+ self.string, self.partially_preserve_email_username = string, False
+ self.preserve_phone_country_code = self.preserve_email_hostname = False
def filtered(self):
output = self.string
for x in re.findall('{}@{}'.format(
Validations.REGEX['email'], Validations.REGEX[
'host']), self.string):
output = re.sub(re.escape(x), self.filter_email(
x), output)
for x in re.findall(
Validations.REGEX['phone'], self.string):
output = re.sub(re.escape(x), self.filter_phone(x), output)
return output
def filter_phone(self, string):
return string[0:4] + ' [FILTERED]' \
if self.preserve_phone_country_code and \
string.startswith('+') else '[PHONE]'
def filter_email(self, string):
email, host = string.split('@')
if self.partially_preserve_email_username:
pos = 0 if len(email) < 6 else 3
elif self.preserve_email_hostname:
pos = 0
- else: return '[EMAIL]'
+ else:
+ return '[EMAIL]'
return '{}[FILTERED]@{}'.format(email[0:pos], host)
class Validations:
REGEX = {
'email': '[a-z0-9][a-z0-9_\+\.-]{0,200}',
'number': '-?[0-9]+(?:\.[0-9])?[0-9]*',
'date': '[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[01])',
'time': '(?:[01][0-9]|2[0-3]):{0}:{0}$'.format('[0-5][0-9]'),
'phone': '(?:(?:0[1-9]|\+)|(?:00|\+[1-9][0-9]{0,2}))'
'(?:[ -()]{0,2}[0-9]){6,11}',
'host': '(?:{0})*?{0}{1}(?:\.{1})?'.format(
'[a-z0-9][a-z0-9-]{0,61}[a-z0-9]\.', '[a-z]{2,3}'),
'number': '-?[0-9]+(?:\.[0-9])?[0-9]*'
}
@staticmethod
def start_end_re(regex):
return '^{}$'.format(regex)
@classmethod
def is_email(cls, string):
if string.count('@') != 1: return False
email, host = string.split('@')
return re.match(cls.start_end_re(
cls.REGEX['email']), email, re.I) and cls.is_hostname(host)
@classmethod
def is_hostname(cls, string):
- return re.match(
- cls.start_end_re(cls.REGEX['host']), string, re.I)
+ return re.match(cls.start_end_re(cls.REGEX['host']), string, re.I)
@classmethod
def is_ip_address(cls, string):
- return len([x for x in string.split('.') \
- if int(x) in range(0, 256)]) == 4
+ if string.count('.') != 3: return False
+ return all(int(x) in range(256) for x in string.split('.'))
@classmethod
def is_number(cls, string):
- return re.match(cls.start_end_re(
- cls.REGEX['number']), string)
+ return re.match(cls.start_end_re(cls.REGEX['number']), string)
@classmethod
def is_integer(cls, string):
return string.count('.') == 0 and cls.is_number(string)
@classmethod
def is_date(cls, string):
- return re.match(cls.start_end_re(
- cls.REGEX['date']), string)
+ return re.match(cls.start_end_re(cls.REGEX['date']), string)
@classmethod
def is_time(cls, string):
- return re.match(cls.start_end_re(
- cls.REGEX['time']), string)
+ return re.match(cls.start_end_re(cls.REGEX['time']), string)
@classmethod
def is_datetime(cls, string):
if len(string) != 19: return False
return cls.is_date(string[0:10]) and cls.is_time(string[-8:])
@classmethod
def is_phone(cls, string):
- return re.match(cls.start_end_re(
- cls.REGEX['phone']), string)
+ return re.match(cls.start_end_re(cls.REGEX['phone']), string)