Решение на Регулярни изрази от Димитър Трендафилов

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

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

Резултати

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

Код

import re
PATTERNS = {}
PATTERNS["is_phone"] = (r'((\b00|\+)[1-9]\d{0,2}|((?<=[^a-zA-Z0-9\+])|^)'
r'0(?=[^0]))([- \(\)]{0,2}\d){6,11}\b')
PATTERNS["is_hostname"] = (r'((([a-zA-Z0-9]([a-zA-Z0-9-]{,61}[a-zA-Z0-9])?)\.)'
r'+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})*)\b')
PATTERNS["is_email"] = r'\b[a-zA-Z0-9][\w\+-\.]{,200}@' \
+ PATTERNS['is_hostname']
PATTERNS["is_ip_address"] = (r'((1\d\d|[1-9]\d|\d|25[0-5]|2[0-4]\d)\.)'
r'{3}(1\d\d|25[0-5]|2[0-4]\d|[1-9]\d|\d)')
PATTERNS["is_integer"] = r'[-]?(0|[1-9]\d*)'
PATTERNS["is_number"] = r'[-]?(0\.\d+|0|[1-9]\d*(\.\d*[1-9])?)'
PATTERNS["is_date"] = r'\d{4}[-](0[1-9]|1[012])[-](0[1-9]|[12]\d|3[01])'
PATTERNS["is_time"] = r'(0\d|1\d|2[0-3])(:(0\d|[1-5]\d)){2}'
PATTERNS["is_datetime"] = PATTERNS['is_date'] + r'[ T]' + PATTERNS['is_time']
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
def filter_phone(self):
if not self.preserve_phone_country_code:
return re.sub(PATTERNS['is_phone'], "[PHONE]", self.text, 0, re.A)
def code_flag(match):
if match.group(1) == '0':
return '[PHONE]'
return match.group(1) + ' [FILTERED]'
return re.sub(PATTERNS['is_phone'], code_flag, self.text, 0, re.A)
def filter_email(self):
def host_flag(match):
return '[FILTERED]@' + match.group(1)
if self.preserve_email_hostname:
return re.sub(PATTERNS['is_email'], host_flag, self.text, 0, re.A)
def username_flag(match):
if len(match.group(0)) - len(match.group(1)) < 7:
return host_flag(match)
return match.group(0)[:3] + '[FILTERED]@' + match.group(1)
if self.partially_preserve_email_username:
return re.sub(PATTERNS['is_email'], username_flag,
self.text, 0, re.A)
return re.sub(PATTERNS['is_email'], '[EMAIL]', self.text, 0, re.A)
def filtered(self):
result = self
result.text = self.filter_phone()
return result.filter_email()
def generator():
def generate(name):
def result(value):
return re.match(PATTERNS[name] + '$', value, re.A)
return result
for name in PATTERNS:
yield (name, generate(name))
Validations = type("", (), {key: function for key, function in generator()})

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

....F..........FF.....FF..FFF..........
======================================================================
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-o616fe/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_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-o616fe/test.py", line 124, in test_can_validate_more_complex_emails
    self.assertIs(solution.Validations.is_email(email), valid)
AssertionError: None 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-o616fe/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 0xb77818b8> 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-o616fe/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: <_sre.SRE_Match object at 0xb7825d90> 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-o616fe/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 0xb7785260> 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-o616fe/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 0xb7827a88> 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-o616fe/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 0xb7825ed0> 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-o616fe/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 0xb77852c0> is not True

----------------------------------------------------------------------
Ran 39 tests in 0.045s

FAILED (failures=8)

История (5 версии и 2 коментара)

Димитър обнови решението на 21.04.2014 01:22 (преди над 10 години)

+import re
+
+
+PATTERNS = {}
+
+PATTERNS["is_phone"] = (r'((\b00|\+)[1-9]\d{0,2}|(?<=[^a-zA-Z0-9\+])'
+ r'0(?=[^0]))([- \(\)]{0,2}\d){6,11}')
+
+PATTERNS["is_hostname"] = (r'((([a-zA-Z0-9]([a-zA-Z0-9-]{,61}[a-zA-Z0-9])?)\.)'
+ r'+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})*)\b')
+
+PATTERNS["is_email"] = r'\b[a-zA-Z0-9][\w\+-\.]{,200}@' \
+ + PATTERNS['is_hostname']
+
+PATTERNS["is_ip_address"] = (r'((1\d\d|[1-9]\d|\d|25[0-5]|2[0-4]\d)\.)'
+ r'{3}(1\d\d|25[0-5]|2[0-4]\d|[1-9]\d|\d)')
+
+PATTERNS["is_integer"] = r'[-]?(0|[1-9]\d*)'
+
+PATTERNS["is_number"] = r'[-]?(0\.\d+|0|[1-9]\d*(\.\d*[1-9])?)'
+
+PATTERNS["is_date"] = r'\d{4}[-](0[1-9]|1[012])[-](0[1-9]|[12]\d|3[01])'
+
+PATTERNS["is_time"] = r'(0\d|1\d|2[0-3])(:(0\d|[1-5]\d)){2}'
+
+PATTERNS["is_datetime"] = PATTERNS['is_date'] + r'[\sT]' + PATTERNS['is_time']
+
+
+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
+
+ def filter_phone(self):
+ if not self.preserve_phone_country_code:
+ return re.sub(PATTERNS['is_phone'], "[PHONE]", self.text, 0, re.A)
+
+ def code_flag(match):
+ if match.group(1) == '0':
+ return '[PHONE]'
+ return match.group(1) + ' [FILTERED]'
+ return re.sub(PATTERNS['is_phone'], code_flag, self.text, 0, re.A)
+
+ def filter_email(self):
+ def host_flag(match):
+ return '[FILTERED]@' + match.group(1)
+
+ if self.preserve_email_hostname:
+ return re.sub(PATTERNS['is_email'], host_flag, self.text, 0, re.A)
+
+ def username_flag(match):
+ if len(match.group(0)) - len(match.group(1)) <= 7:
+ return host_flag(match)
+ return match.group(0)[:3] + '[FILTERED]@' + match.group(1)
+
+ if self.partially_preserve_email_username:
+ return re.sub(PATTERNS['is_email'], username_flag,
+ self.text, 0, re.A)
+ return re.sub(PATTERNS['is_email'], '[EMAIL]', self.text, 0, re.A)
+
+ def filtered(self):
+ result = self
+ result.text = self.filter_phone()
+ return result.filter_email()
+
+
+def generator():
+ def generate(name):
+ def result(value):
+ return not re.sub(PATTERNS[name], '', value, 1, re.A)
+ return result
+ for name in PATTERNS:
+ yield (name, generate(name))
+
+Validations = type("", (), {key: function for key, function in generator()})

Димитър обнови решението на 21.04.2014 03:32 (преди над 10 години)

import re
PATTERNS = {}
-PATTERNS["is_phone"] = (r'((\b00|\+)[1-9]\d{0,2}|(?<=[^a-zA-Z0-9\+])'
- r'0(?=[^0]))([- \(\)]{0,2}\d){6,11}')
+PATTERNS["is_phone"] = (r'((\b00|\+)[1-9]\d{0,2}|((?<=[^a-zA-Z0-9\+])|^)'
+ r'0(?=[^0]))([- \(\)]{0,2}\d){6,11}\b')
PATTERNS["is_hostname"] = (r'((([a-zA-Z0-9]([a-zA-Z0-9-]{,61}[a-zA-Z0-9])?)\.)'
r'+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})*)\b')
PATTERNS["is_email"] = r'\b[a-zA-Z0-9][\w\+-\.]{,200}@' \
+ PATTERNS['is_hostname']
PATTERNS["is_ip_address"] = (r'((1\d\d|[1-9]\d|\d|25[0-5]|2[0-4]\d)\.)'
r'{3}(1\d\d|25[0-5]|2[0-4]\d|[1-9]\d|\d)')
PATTERNS["is_integer"] = r'[-]?(0|[1-9]\d*)'
PATTERNS["is_number"] = r'[-]?(0\.\d+|0|[1-9]\d*(\.\d*[1-9])?)'
PATTERNS["is_date"] = r'\d{4}[-](0[1-9]|1[012])[-](0[1-9]|[12]\d|3[01])'
PATTERNS["is_time"] = r'(0\d|1\d|2[0-3])(:(0\d|[1-5]\d)){2}'
PATTERNS["is_datetime"] = PATTERNS['is_date'] + r'[\sT]' + PATTERNS['is_time']
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
def filter_phone(self):
if not self.preserve_phone_country_code:
return re.sub(PATTERNS['is_phone'], "[PHONE]", self.text, 0, re.A)
def code_flag(match):
if match.group(1) == '0':
return '[PHONE]'
return match.group(1) + ' [FILTERED]'
return re.sub(PATTERNS['is_phone'], code_flag, self.text, 0, re.A)
def filter_email(self):
def host_flag(match):
return '[FILTERED]@' + match.group(1)
if self.preserve_email_hostname:
return re.sub(PATTERNS['is_email'], host_flag, self.text, 0, re.A)
def username_flag(match):
if len(match.group(0)) - len(match.group(1)) <= 7:
return host_flag(match)
return match.group(0)[:3] + '[FILTERED]@' + match.group(1)
if self.partially_preserve_email_username:
return re.sub(PATTERNS['is_email'], username_flag,
self.text, 0, re.A)
return re.sub(PATTERNS['is_email'], '[EMAIL]', self.text, 0, re.A)
def filtered(self):
result = self
result.text = self.filter_phone()
return result.filter_email()
def generator():
def generate(name):
def result(value):
return not re.sub(PATTERNS[name], '', value, 1, re.A)
return result
for name in PATTERNS:
yield (name, generate(name))
Validations = type("", (), {key: function for key, function in generator()})

Димитър обнови решението на 22.04.2014 23:06 (преди над 10 години)

import re
PATTERNS = {}
PATTERNS["is_phone"] = (r'((\b00|\+)[1-9]\d{0,2}|((?<=[^a-zA-Z0-9\+])|^)'
r'0(?=[^0]))([- \(\)]{0,2}\d){6,11}\b')
PATTERNS["is_hostname"] = (r'((([a-zA-Z0-9]([a-zA-Z0-9-]{,61}[a-zA-Z0-9])?)\.)'
r'+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})*)\b')
PATTERNS["is_email"] = r'\b[a-zA-Z0-9][\w\+-\.]{,200}@' \
+ PATTERNS['is_hostname']
PATTERNS["is_ip_address"] = (r'((1\d\d|[1-9]\d|\d|25[0-5]|2[0-4]\d)\.)'
r'{3}(1\d\d|25[0-5]|2[0-4]\d|[1-9]\d|\d)')
PATTERNS["is_integer"] = r'[-]?(0|[1-9]\d*)'
PATTERNS["is_number"] = r'[-]?(0\.\d+|0|[1-9]\d*(\.\d*[1-9])?)'
PATTERNS["is_date"] = r'\d{4}[-](0[1-9]|1[012])[-](0[1-9]|[12]\d|3[01])'
PATTERNS["is_time"] = r'(0\d|1\d|2[0-3])(:(0\d|[1-5]\d)){2}'
PATTERNS["is_datetime"] = PATTERNS['is_date'] + r'[\sT]' + PATTERNS['is_time']
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
def filter_phone(self):
if not self.preserve_phone_country_code:
return re.sub(PATTERNS['is_phone'], "[PHONE]", self.text, 0, re.A)
def code_flag(match):
if match.group(1) == '0':
return '[PHONE]'
return match.group(1) + ' [FILTERED]'
return re.sub(PATTERNS['is_phone'], code_flag, self.text, 0, re.A)
def filter_email(self):
def host_flag(match):
return '[FILTERED]@' + match.group(1)
if self.preserve_email_hostname:
return re.sub(PATTERNS['is_email'], host_flag, self.text, 0, re.A)
def username_flag(match):
if len(match.group(0)) - len(match.group(1)) <= 7:
return host_flag(match)
return match.group(0)[:3] + '[FILTERED]@' + match.group(1)
if self.partially_preserve_email_username:
return re.sub(PATTERNS['is_email'], username_flag,
self.text, 0, re.A)
return re.sub(PATTERNS['is_email'], '[EMAIL]', self.text, 0, re.A)
def filtered(self):
result = self
result.text = self.filter_phone()
return result.filter_email()
def generator():
def generate(name):
def result(value):
- return not re.sub(PATTERNS[name], '', value, 1, re.A)
+ return re.match(PATTERNS[name] + '$', value, re.A)
return result
for name in PATTERNS:
yield (name, generate(name))
Validations = type("", (), {key: function for key, function in generator()})

Димитър обнови решението на 23.04.2014 12:07 (преди над 10 години)

import re
PATTERNS = {}
PATTERNS["is_phone"] = (r'((\b00|\+)[1-9]\d{0,2}|((?<=[^a-zA-Z0-9\+])|^)'
r'0(?=[^0]))([- \(\)]{0,2}\d){6,11}\b')
PATTERNS["is_hostname"] = (r'((([a-zA-Z0-9]([a-zA-Z0-9-]{,61}[a-zA-Z0-9])?)\.)'
r'+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})*)\b')
PATTERNS["is_email"] = r'\b[a-zA-Z0-9][\w\+-\.]{,200}@' \
+ PATTERNS['is_hostname']
PATTERNS["is_ip_address"] = (r'((1\d\d|[1-9]\d|\d|25[0-5]|2[0-4]\d)\.)'
r'{3}(1\d\d|25[0-5]|2[0-4]\d|[1-9]\d|\d)')
PATTERNS["is_integer"] = r'[-]?(0|[1-9]\d*)'
PATTERNS["is_number"] = r'[-]?(0\.\d+|0|[1-9]\d*(\.\d*[1-9])?)'
PATTERNS["is_date"] = r'\d{4}[-](0[1-9]|1[012])[-](0[1-9]|[12]\d|3[01])'
PATTERNS["is_time"] = r'(0\d|1\d|2[0-3])(:(0\d|[1-5]\d)){2}'
PATTERNS["is_datetime"] = PATTERNS['is_date'] + r'[\sT]' + PATTERNS['is_time']
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
def filter_phone(self):
if not self.preserve_phone_country_code:
return re.sub(PATTERNS['is_phone'], "[PHONE]", self.text, 0, re.A)
def code_flag(match):
if match.group(1) == '0':
return '[PHONE]'
return match.group(1) + ' [FILTERED]'
return re.sub(PATTERNS['is_phone'], code_flag, self.text, 0, re.A)
def filter_email(self):
def host_flag(match):
return '[FILTERED]@' + match.group(1)
if self.preserve_email_hostname:
return re.sub(PATTERNS['is_email'], host_flag, self.text, 0, re.A)
def username_flag(match):
- if len(match.group(0)) - len(match.group(1)) <= 7:
+ if len(match.group(0)) - len(match.group(1)) < 7:
return host_flag(match)
return match.group(0)[:3] + '[FILTERED]@' + match.group(1)
if self.partially_preserve_email_username:
return re.sub(PATTERNS['is_email'], username_flag,
self.text, 0, re.A)
return re.sub(PATTERNS['is_email'], '[EMAIL]', self.text, 0, re.A)
def filtered(self):
result = self
result.text = self.filter_phone()
return result.filter_email()
def generator():
def generate(name):
def result(value):
return re.match(PATTERNS[name] + '$', value, re.A)
return result
for name in PATTERNS:
yield (name, generate(name))
Validations = type("", (), {key: function for key, function in generator()})

Димитър обнови решението на 23.04.2014 15:38 (преди над 10 години)

import re
PATTERNS = {}
PATTERNS["is_phone"] = (r'((\b00|\+)[1-9]\d{0,2}|((?<=[^a-zA-Z0-9\+])|^)'
r'0(?=[^0]))([- \(\)]{0,2}\d){6,11}\b')
PATTERNS["is_hostname"] = (r'((([a-zA-Z0-9]([a-zA-Z0-9-]{,61}[a-zA-Z0-9])?)\.)'
r'+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})*)\b')
PATTERNS["is_email"] = r'\b[a-zA-Z0-9][\w\+-\.]{,200}@' \
+ PATTERNS['is_hostname']
PATTERNS["is_ip_address"] = (r'((1\d\d|[1-9]\d|\d|25[0-5]|2[0-4]\d)\.)'
r'{3}(1\d\d|25[0-5]|2[0-4]\d|[1-9]\d|\d)')
PATTERNS["is_integer"] = r'[-]?(0|[1-9]\d*)'
PATTERNS["is_number"] = r'[-]?(0\.\d+|0|[1-9]\d*(\.\d*[1-9])?)'
PATTERNS["is_date"] = r'\d{4}[-](0[1-9]|1[012])[-](0[1-9]|[12]\d|3[01])'
PATTERNS["is_time"] = r'(0\d|1\d|2[0-3])(:(0\d|[1-5]\d)){2}'
-PATTERNS["is_datetime"] = PATTERNS['is_date'] + r'[\sT]' + PATTERNS['is_time']
+PATTERNS["is_datetime"] = PATTERNS['is_date'] + r'[ T]' + PATTERNS['is_time']
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
def filter_phone(self):
if not self.preserve_phone_country_code:
return re.sub(PATTERNS['is_phone'], "[PHONE]", self.text, 0, re.A)
def code_flag(match):
if match.group(1) == '0':
return '[PHONE]'
return match.group(1) + ' [FILTERED]'
return re.sub(PATTERNS['is_phone'], code_flag, self.text, 0, re.A)
def filter_email(self):
def host_flag(match):
return '[FILTERED]@' + match.group(1)
if self.preserve_email_hostname:
return re.sub(PATTERNS['is_email'], host_flag, self.text, 0, re.A)
def username_flag(match):
if len(match.group(0)) - len(match.group(1)) < 7:
return host_flag(match)
return match.group(0)[:3] + '[FILTERED]@' + match.group(1)
if self.partially_preserve_email_username:
return re.sub(PATTERNS['is_email'], username_flag,
self.text, 0, re.A)
return re.sub(PATTERNS['is_email'], '[EMAIL]', self.text, 0, re.A)
def filtered(self):
result = self
result.text = self.filter_phone()
return result.filter_email()
def generator():
def generate(name):
def result(value):
return re.match(PATTERNS[name] + '$', value, re.A)
return result
for name in PATTERNS:
yield (name, generate(name))
Validations = type("", (), {key: function for key, function in generator()})