Решение на Регулярни изрази от Веселин Генадиев

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

Към профила на Веселин Генадиев

Резултати

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

Код

import re
HOSTNAME = (r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{,60}'
r'[a-zA-Z0-9])\.)+([A-Za-z]{2,3}(\.[A-Za-z]{2})?)$')
USERNAME = r'[a-zA-Z0-9][a-zA-Z0-9_+.-]{,200}'
EMAIL = r'^\b{}@{}\b$'.format(USERNAME, HOSTNAME[1:-1])
LOCAL_PHONE = r'^\b0[-() ]?[1-9]([-() ]?[0-9]){5,10}\b$'
INTERNATIONAL_PHONE_PREFIX = r'((00)|\+)[1-9][0-9]{,2}'
INTERNATIONAL_PHONE_SUFFIX = r'[-() ]{,2}[1-9]([-() ]{,2}[0-9]){5,10}'
INTERNATIONAL_PHONE = r'^{}{}\b$'.format(INTERNATIONAL_PHONE_PREFIX,
INTERNATIONAL_PHONE_SUFFIX)
IP_ADDRESS = (r'^(([0-9]|[1-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
r'([0-9]|[1-9][0-9]|2[0-4][0-9]|25[0-5])$')
NUMBER = r'^\-?(0|[1-9][0-9]*)(\.[0-9])?[0-9]*$'
INTEGER = r'^\-?(0|[1-9][0-9]*)$'
DATE = r'^[0-9]{4}\-(0[1-9]|1[0-2])\-(0[1-9]|[12][0-9]|3[0-1])$'
TIME = r'^([0-1][0-9]|2[0-3])(:[0-5][0-9]){2}$'
DATETIME = r'^{}[ T]{}$'.format(DATE[1:-1], TIME[1:-1])
def matches(pattern, value):
return re.match(pattern, value) is not None
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):
text = re.sub(LOCAL_PHONE[1:-1], '[PHONE]', self.__text)
filter_phone = lambda phone: self.filter_phone(phone.group())
text = re.sub(INTERNATIONAL_PHONE[1:-1], filter_phone, text)
filter_email = lambda email: self.filter_email(email.group())
text = re.sub(EMAIL[1:-1], filter_email, text)
return text
def filter_phone(self, phone):
if ((re.match(INTERNATIONAL_PHONE, phone) and
self.preserve_phone_country_code)):
return (re.match(INTERNATIONAL_PHONE_PREFIX, phone).group()
+ ' [FILTERED]')
else:
return '[PHONE]'
def filter_email(self, email):
if email.index('@') >= 6 and self.partially_preserve_email_username:
filter_username = lambda match: match.group()[0:3] + '[FILTERED]'
return re.sub(USERNAME, filter_username, email, 1)
elif (self.partially_preserve_email_username or
self.preserve_email_hostname):
return re.sub(USERNAME, '[FILTERED]', email, 1)
else:
return '[EMAIL]'
class Validations:
@classmethod
def is_hostname(cls, value):
return matches(HOSTNAME, value)
@classmethod
def is_email(cls, value):
return matches(EMAIL, value)
@classmethod
def is_phone(cls, value):
return (matches(LOCAL_PHONE, value) or
matches(INTERNATIONAL_PHONE, value))
@classmethod
def is_ip_address(cls, value):
return matches(IP_ADDRESS, value)
@classmethod
def is_number(cls, value):
return matches(NUMBER, value)
@classmethod
def is_integer(cls, value):
return matches(INTEGER, value)
@classmethod
def is_date(cls, value):
return matches(DATE, value)
@classmethod
def is_time(cls, value):
return matches(TIME, value)
@classmethod
def is_datetime(cls, value):
return matches(DATETIME, value)

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

....F...........F.....FF..FF.......F...
======================================================================
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-12zb62t/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_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-12zb62t/test.py", line 160, in test_can_validate_more_complex_phone_numbers
    self.assertIs(solution.Validations.is_phone(phone), valid)
AssertionError: False 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-12zb62t/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-12zb62t/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-12zb62t/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-12zb62t/test.py", line 288, in test_handles_newlines_in_time_and_datetime_validation
    self.assertFalse(solution.Validations.is_time("12:01:01\n"))
AssertionError: True is not false

======================================================================
FAIL: test_validates_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-12zb62t/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.053s

FAILED (failures=7)

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

Веселин обнови решението на 21.04.2014 01:08 (преди около 10 години)

+import re
+
+
+HOSTNAME = (r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{,60}'
+ r'[a-zA-Z0-9])\.)+([A-Za-z]{2,3}(\.[A-Za-z]{2})?)$')
+USERNAME = r'[a-zA-Z0-9][a-zA-Z0-9_+.-]{,200}'
+EMAIL = r'^{}@{}$'.format(USERNAME, HOSTNAME[1:-1])
+LOCAL_PHONE = r'^0[-() ]?[1-9]([-() ]?[0-9]){5,10}$'
+INTERNATIONAL_PHONE_PREFIX = r'((00)|\+)[1-9][0-9]{,2}'
+INTERNATIONAL_PHONE_SUFFIX = r'[-() ]{,2}?[1-9]([-() ]{,2}?[0-9]){5,10}'
+INTERNATIONAL_PHONE = r'^{}{}$'.format(INTERNATIONAL_PHONE_PREFIX,
+ INTERNATIONAL_PHONE_SUFFIX)
+IP_ADDRESS = (r'^(([0-9]|[1-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+ r'([0-9]|[1-9][0-9]|2[0-4][0-9]|25[0-5])$')
+NUMBER = r'^\-?(0|[1-9][0-9]*)\.?[0-9]+$'
+INTEGER = r'^\-?(0|[1-9][0-9]*)$'
+DATE = r'^[0-9]{4}\-(0[1-9]|1[0-2])\-(0[1-9]|[12][0-9]|3[0-1])$'
+TIME = r'^([0-1][0-9]|2[0-3])(:[0-5][0-9]){2}$'
+DATETIME = r'^{}[ T]{}$'.format(DATE[1:-1], TIME[1:-1])
+
+
+def matches(pattern, value):
+ return re.match(pattern, value) is not None
+
+
+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):
+ text = re.sub(LOCAL_PHONE[1:-1], '[PHONE]', self.__text)
+ filter_phone = lambda phone: self.filter_phone(phone.group())
+ text = re.sub(INTERNATIONAL_PHONE[1:-1], filter_phone, text)
+ filter_email = lambda email: self.filter_email(email.group())
+ text = re.sub(EMAIL[1:-1], filter_email, text)
+ return text
+
+ def filter_phone(self, phone):
+ if ((re.match(INTERNATIONAL_PHONE, phone) and
+ self.preserve_phone_country_code)):
+ return (re.match(INTERNATIONAL_PHONE_PREFIX, phone).group()
+ + ' [FILTERED]')
+ else:
+ return '[PHONE]'
+
+ def filter_email(self, email):
+ if email.index('@') >= 6 and self.partially_preserve_email_username:
+ filter_username = lambda match: match.group()[0:3] + '[FILTERED]'
+ return re.sub(USERNAME, filter_username, email, 1)
+ elif (self.partially_preserve_email_username or
+ self.preserve_email_hostname):
+ return re.sub(USERNAME, '[FILTERED]', email, 1)
+ else:
+ return '[EMAIL]'
+
+
+class Validations:
+ @classmethod
+ def is_hostname(cls, value):
+ return matches(HOSTNAME, value)
+
+ @classmethod
+ def is_email(cls, value):
+ return matches(EMAIL, value)
+
+ @classmethod
+ def is_phone(cls, value):
+ return (matches(LOCAL_PHONE, value) or
+ matches(INTERNATIONAL_PHONE, value))
+
+ @classmethod
+ def is_ip_address(cls, value):
+ return matches(IP_ADDRESS, value)
+
+ @classmethod
+ def is_number(cls, value):
+ return matches(NUMBER, value)
+
+ @classmethod
+ def is_integer(cls, value):
+ return matches(INTEGER, value)
+
+ @classmethod
+ def is_date(cls, value):
+ return matches(DATE, value)
+
+ @classmethod
+ def is_time(cls, value):
+ return matches(TIME, value)
+
+ @classmethod
+ def is_datetime(cls, value):
+ return matches(DATETIME, value)

Веселин обнови решението на 23.04.2014 01:39 (преди около 10 години)

import re
HOSTNAME = (r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{,60}'
r'[a-zA-Z0-9])\.)+([A-Za-z]{2,3}(\.[A-Za-z]{2})?)$')
USERNAME = r'[a-zA-Z0-9][a-zA-Z0-9_+.-]{,200}'
-EMAIL = r'^{}@{}$'.format(USERNAME, HOSTNAME[1:-1])
-LOCAL_PHONE = r'^0[-() ]?[1-9]([-() ]?[0-9]){5,10}$'
+EMAIL = r'^\b{}@{}\b$'.format(USERNAME, HOSTNAME[1:-1])
+LOCAL_PHONE = r'^\b0[-() ]?[1-9]([-() ]?[0-9]){5,10}\b$'
INTERNATIONAL_PHONE_PREFIX = r'((00)|\+)[1-9][0-9]{,2}'
-INTERNATIONAL_PHONE_SUFFIX = r'[-() ]{,2}?[1-9]([-() ]{,2}?[0-9]){5,10}'
-INTERNATIONAL_PHONE = r'^{}{}$'.format(INTERNATIONAL_PHONE_PREFIX,
- INTERNATIONAL_PHONE_SUFFIX)
+INTERNATIONAL_PHONE_SUFFIX = r'[-() ]{,2}[1-9]([-() ]{,2}[0-9]){5,10}'
+INTERNATIONAL_PHONE = r'^{}{}\b$'.format(INTERNATIONAL_PHONE_PREFIX,
+ INTERNATIONAL_PHONE_SUFFIX)
IP_ADDRESS = (r'^(([0-9]|[1-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
r'([0-9]|[1-9][0-9]|2[0-4][0-9]|25[0-5])$')
-NUMBER = r'^\-?(0|[1-9][0-9]*)\.?[0-9]+$'
+NUMBER = r'^\-?(0|[1-9][0-9]*)(\.[0-9])?[0-9]*$'
INTEGER = r'^\-?(0|[1-9][0-9]*)$'
DATE = r'^[0-9]{4}\-(0[1-9]|1[0-2])\-(0[1-9]|[12][0-9]|3[0-1])$'
TIME = r'^([0-1][0-9]|2[0-3])(:[0-5][0-9]){2}$'
DATETIME = r'^{}[ T]{}$'.format(DATE[1:-1], TIME[1:-1])
def matches(pattern, value):
return re.match(pattern, value) is not None
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):
text = re.sub(LOCAL_PHONE[1:-1], '[PHONE]', self.__text)
filter_phone = lambda phone: self.filter_phone(phone.group())
text = re.sub(INTERNATIONAL_PHONE[1:-1], filter_phone, text)
filter_email = lambda email: self.filter_email(email.group())
text = re.sub(EMAIL[1:-1], filter_email, text)
return text
def filter_phone(self, phone):
if ((re.match(INTERNATIONAL_PHONE, phone) and
self.preserve_phone_country_code)):
return (re.match(INTERNATIONAL_PHONE_PREFIX, phone).group()
+ ' [FILTERED]')
else:
return '[PHONE]'
def filter_email(self, email):
if email.index('@') >= 6 and self.partially_preserve_email_username:
filter_username = lambda match: match.group()[0:3] + '[FILTERED]'
return re.sub(USERNAME, filter_username, email, 1)
elif (self.partially_preserve_email_username or
self.preserve_email_hostname):
return re.sub(USERNAME, '[FILTERED]', email, 1)
else:
return '[EMAIL]'
class Validations:
@classmethod
def is_hostname(cls, value):
return matches(HOSTNAME, value)
@classmethod
def is_email(cls, value):
return matches(EMAIL, value)
@classmethod
def is_phone(cls, value):
return (matches(LOCAL_PHONE, value) or
matches(INTERNATIONAL_PHONE, value))
@classmethod
def is_ip_address(cls, value):
return matches(IP_ADDRESS, value)
@classmethod
def is_number(cls, value):
return matches(NUMBER, value)
@classmethod
def is_integer(cls, value):
return matches(INTEGER, value)
@classmethod
def is_date(cls, value):
return matches(DATE, value)
@classmethod
def is_time(cls, value):
return matches(TIME, value)
@classmethod
def is_datetime(cls, value):
return matches(DATETIME, value)