Решение на Регулярни изрази от Любомир Коев

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

Към профила на Любомир Коев

Резултати

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

Код

import re
class Validations:
ip_regex = r'(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
int_regex = r'-?([1-9]\d*|0)'
fraction_regex = r'-?\d+\.\d+'
date_regex = r'\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2]\d|3[0-1])'
time_regex = r'(?:2[0-3]|[0-1]\d):[0-5][0-9]:[0-5][0-9]'
datetime_regex = date_regex + r'(?:T| |\b)' + time_regex
local_phone_regex = r'0[1-9]*\d*(?:[ -\(\)]{,2}\d){6,11}'
international_phone_regex = r'(?:00|\+)[1-9]\d{,2}(?:[ -\(\)]{,2}\d){6,11}'
host_regex = r'(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{,61}[a-zA-Z0-9])\.)+(?:[a-zA-Z]{2}|[a-zA-Z]{3}|[a-zA-Z]{2}\.[a-zA-Z]{2}|[a-zA-Z]{3}\.[a-zA-Z]{2})'
email_name_regex = r'(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9_+\.\-]{,199})'
@staticmethod
def _format_regex(*args):
return '^' + ''.join(args) + '$'
@classmethod
def is_email(cls, value):
return bool(re.match(
cls._format_regex(cls.email_name_regex, '@', cls.host_regex),
value
))
@classmethod
def is_phone(cls, value):
return bool(
re.match(cls._format_regex(cls.local_phone_regex), value) or
re.match(cls._format_regex(cls.international_phone_regex), value)
)
@classmethod
def is_hostname(cls, value):
return bool(re.match(cls._format_regex(cls.host_regex), value))
@classmethod
def is_ip_address(cls, value):
return bool(re.match(cls._format_regex(cls.ip_regex), value))
@classmethod
def is_number(cls, value):
return bool(
cls.is_integer(value) or
re.match(cls._format_regex(cls.fraction_regex), value)
)
@classmethod
def is_integer(cls, value):
return bool(re.match(cls._format_regex(cls.int_regex), value))
@classmethod
def is_date(cls, value):
return bool(re.match(cls._format_regex(cls.date_regex), value))
@classmethod
def is_time(cls, value):
return bool(re.match(cls._format_regex(cls.time_regex), value))
@classmethod
def is_datetime(cls, value):
return bool(re.match(cls._format_regex(cls.datetime_regex), value))
class PrivacyFilter:
filter_string = '[FILTERED]'
email_string = '[EMAIL]'
phone_string = '[PHONE]'
preserve_phone_country_code = False
preserve_email_hostname = False
partially_preserve_email_username = False
mail_regex = r'\b({})({})\b'.format(
Validations.email_name_regex, '@' + Validations.host_regex
)
local_phone_regex = r'\b({})\b'.format(Validations.local_phone_regex)
international_phone_regex = r'([^\w\d\+])({})\b'.format(
Validations.international_phone_regex
)
def __init__(self, text):
self.unfiltered = text
def filtered(self):
return self.filter_phone(self.filter_mail(self.unfiltered))
def filter_mail(self, text):
return re.sub(self.mail_regex, self.mail_replace, text)
def mail_replace(self, match_object):
if self.partially_preserve_email_username:
name = self.filter_string
if len(match_object.group(1)) >= 6:
name = match_object.group(1)[0:3] + name
return name + match_object.group(2)
elif self.preserve_email_hostname:
return self.filter_string + match_object.group(2)
else:
return self.email_string
def filter_phone(self, text):
return re.sub(
self.local_phone_regex,
self.phone_string,
re.sub(
self.international_phone_regex,
self.phone_replace,
text
)
)
def phone_replace(self, match_object):
if not self.preserve_phone_country_code:
return self.phone_string
return match_object.group(1) + re.match(
r'(?:00|\+)[1-9]\d{,2}',
match_object.group(2)
).group(0) + ' ' + self.filter_string

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

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


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

----------------------------------------------------------------------
Ran 39 tests in 0.062s

FAILED (failures=8)

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

Любомир обнови решението на 23.04.2014 13:54 (преди над 10 години)

+import re
+
+
+class Validations:
+ ip_regex = r'(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
+
+ int_regex = r'-?([1-9]\d*|0)'
+ fraction_regex = r'-?\d+\.\d+'
+
+ date_regex = r'\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2]\d|3[0-1])'
+ time_regex = r'(?:2[0-3]|[0-1]\d):[0-5][0-9]:[0-5][0-9]'
+ datetime_regex = date_regex + r'(?:T| |\b)' + time_regex
+
+ local_phone_regex = r'0[1-9]*\d*(?:[ -\(\)]{,2}\d){6,11}'
+ international_phone_regex = r'(?:00|\+)[1-9]\d{,2}(?:[ -\(\)]{,2}\d){6,11}'
+
+ host_regex = r'(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{,61}[a-zA-Z0-9])\.)+(?:[a-zA-Z]{2}|[a-zA-Z]{3}|[a-zA-Z]{2}\.[a-zA-Z]{2}|[a-zA-Z]{3}\.[a-zA-Z]{2})'
+ email_name_regex = r'(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9_+\.\-]{,199})'
+
+ @staticmethod
+ def _format_regex(*args):
+ return '^' + ''.join(args) + '$'
+
+ @classmethod
+ def is_email(cls, value):
+ return bool(re.match(
+ cls._format_regex(cls.email_name_regex, '@', cls.host_regex),
+ value
+ ))
+
+ @classmethod
+ def is_phone(cls, value):
+ return bool(
+ re.match(cls._format_regex(cls.local_phone_regex), value) or
+ re.match(cls._format_regex(cls.international_phone_regex), value)
+ )
+
+ @classmethod
+ def is_hostname(cls, value):
+ return bool(re.match(cls._format_regex(cls.host_regex), value))
+
+ @classmethod
+ def is_ip_address(cls, value):
+ return bool(re.match(cls._format_regex(cls.ip_regex), value))
+
+ @classmethod
+ def is_number(cls, value):
+ return bool(
+ cls.is_integer(value) or
+ re.match(cls._format_regex(cls.fraction_regex), value)
+ )
+
+ @classmethod
+ def is_integer(cls, value):
+ return bool(re.match(cls._format_regex(cls.int_regex), value))
+
+ @classmethod
+ def is_date(cls, value):
+ return bool(re.match(cls._format_regex(cls.date_regex), value))
+
+ @classmethod
+ def is_time(cls, value):
+ return bool(re.match(cls._format_regex(cls.time_regex), value))
+
+ @classmethod
+ def is_datetime(cls, value):
+ return bool(re.match(cls._format_regex(cls.datetime_regex), value))
+
+
+class PrivacyFilter:
+ filter_string = '[FILTERED]'
+ email_string = '[EMAIL]'
+ phone_string = '[PHONE]'
+
+ preserve_phone_country_code = False
+ preserve_email_hostname = False
+ partially_preserve_email_username = False
+
+ mail_regex = r'\b({})({})\b'.format(
+ Validations.email_name_regex, '@' + Validations.host_regex
+ )
+
+ local_phone_regex = r'\b({})\b'.format(Validations.local_phone_regex)
+
+ international_phone_regex = '\b({})\b'.format(
+ Validations.international_phone_regex
+ )
+
+ def __init__(self, text):
+ self.unfiltered = text
+
+ def filtered(self):
+ return self.filter_phone(self.filter_mail(self.unfiltered))
+
+ def filter_mail(self, text):
+ return re.sub(self.mail_regex, self.mail_replace, text)
+
+ def mail_replace(self, match_object):
+ if self.partially_preserve_email_username:
+ name = self.filter_string
+ if len(match_object.group(1)) >= 6:
+ name = match_object.group(1)[0:3] + name
+ return name + match_object.group(2)
+
+ elif self.preserve_email_hostname:
+ return self.filter_string + match_object.group(2)
+
+ else:
+ return self.email_string
+
+
+ def filter_phone(self, text):
+ return re.sub(
+ self.international_phone_regex,
+ self.phone_replace,
+ re.sub(self.local_phone_regex, self.phone_string, text)
+ )
+
+ def phone_replace(self, match_object):
+ if not self.preserve_phone_country_code:
+ return self.phone_string
+
+ return self.phone_string
+

Любомир обнови решението на 23.04.2014 13:56 (преди над 10 години)

import re
class Validations:
ip_regex = r'(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
int_regex = r'-?([1-9]\d*|0)'
fraction_regex = r'-?\d+\.\d+'
date_regex = r'\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2]\d|3[0-1])'
time_regex = r'(?:2[0-3]|[0-1]\d):[0-5][0-9]:[0-5][0-9]'
datetime_regex = date_regex + r'(?:T| |\b)' + time_regex
local_phone_regex = r'0[1-9]*\d*(?:[ -\(\)]{,2}\d){6,11}'
international_phone_regex = r'(?:00|\+)[1-9]\d{,2}(?:[ -\(\)]{,2}\d){6,11}'
host_regex = r'(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{,61}[a-zA-Z0-9])\.)+(?:[a-zA-Z]{2}|[a-zA-Z]{3}|[a-zA-Z]{2}\.[a-zA-Z]{2}|[a-zA-Z]{3}\.[a-zA-Z]{2})'
email_name_regex = r'(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9_+\.\-]{,199})'
@staticmethod
def _format_regex(*args):
return '^' + ''.join(args) + '$'
@classmethod
def is_email(cls, value):
return bool(re.match(
cls._format_regex(cls.email_name_regex, '@', cls.host_regex),
value
))
@classmethod
def is_phone(cls, value):
return bool(
- re.match(cls._format_regex(cls.local_phone_regex), value) or
+ re.match(cls._format_regex(cls.local_phone_regex), value) or
re.match(cls._format_regex(cls.international_phone_regex), value)
)
@classmethod
def is_hostname(cls, value):
return bool(re.match(cls._format_regex(cls.host_regex), value))
@classmethod
def is_ip_address(cls, value):
return bool(re.match(cls._format_regex(cls.ip_regex), value))
@classmethod
def is_number(cls, value):
return bool(
- cls.is_integer(value) or
+ cls.is_integer(value) or
re.match(cls._format_regex(cls.fraction_regex), value)
)
@classmethod
def is_integer(cls, value):
return bool(re.match(cls._format_regex(cls.int_regex), value))
@classmethod
def is_date(cls, value):
return bool(re.match(cls._format_regex(cls.date_regex), value))
@classmethod
def is_time(cls, value):
return bool(re.match(cls._format_regex(cls.time_regex), value))
@classmethod
def is_datetime(cls, value):
return bool(re.match(cls._format_regex(cls.datetime_regex), value))
class PrivacyFilter:
filter_string = '[FILTERED]'
- email_string = '[EMAIL]'
- phone_string = '[PHONE]'
+ email_string = '[EMAIL]'
+ phone_string = '[PHONE]'
preserve_phone_country_code = False
preserve_email_hostname = False
partially_preserve_email_username = False
mail_regex = r'\b({})({})\b'.format(
Validations.email_name_regex, '@' + Validations.host_regex
)
local_phone_regex = r'\b({})\b'.format(Validations.local_phone_regex)
-
+
international_phone_regex = '\b({})\b'.format(
Validations.international_phone_regex
)
def __init__(self, text):
self.unfiltered = text
def filtered(self):
return self.filter_phone(self.filter_mail(self.unfiltered))
def filter_mail(self, text):
return re.sub(self.mail_regex, self.mail_replace, text)
def mail_replace(self, match_object):
if self.partially_preserve_email_username:
name = self.filter_string
if len(match_object.group(1)) >= 6:
name = match_object.group(1)[0:3] + name
return name + match_object.group(2)
elif self.preserve_email_hostname:
return self.filter_string + match_object.group(2)
else:
return self.email_string
-
def filter_phone(self, text):
return re.sub(
self.international_phone_regex,
- self.phone_replace,
+ self.phone_replace,
re.sub(self.local_phone_regex, self.phone_string, text)
)
def phone_replace(self, match_object):
if not self.preserve_phone_country_code:
return self.phone_string
-
+
return self.phone_string
-

Любомир обнови решението на 23.04.2014 15:41 (преди над 10 години)

import re
-
class Validations:
ip_regex = r'(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
int_regex = r'-?([1-9]\d*|0)'
fraction_regex = r'-?\d+\.\d+'
date_regex = r'\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2]\d|3[0-1])'
time_regex = r'(?:2[0-3]|[0-1]\d):[0-5][0-9]:[0-5][0-9]'
datetime_regex = date_regex + r'(?:T| |\b)' + time_regex
local_phone_regex = r'0[1-9]*\d*(?:[ -\(\)]{,2}\d){6,11}'
international_phone_regex = r'(?:00|\+)[1-9]\d{,2}(?:[ -\(\)]{,2}\d){6,11}'
host_regex = r'(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{,61}[a-zA-Z0-9])\.)+(?:[a-zA-Z]{2}|[a-zA-Z]{3}|[a-zA-Z]{2}\.[a-zA-Z]{2}|[a-zA-Z]{3}\.[a-zA-Z]{2})'
email_name_regex = r'(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9_+\.\-]{,199})'
@staticmethod
def _format_regex(*args):
return '^' + ''.join(args) + '$'
@classmethod
def is_email(cls, value):
return bool(re.match(
cls._format_regex(cls.email_name_regex, '@', cls.host_regex),
value
))
@classmethod
def is_phone(cls, value):
return bool(
re.match(cls._format_regex(cls.local_phone_regex), value) or
re.match(cls._format_regex(cls.international_phone_regex), value)
)
@classmethod
def is_hostname(cls, value):
return bool(re.match(cls._format_regex(cls.host_regex), value))
@classmethod
def is_ip_address(cls, value):
return bool(re.match(cls._format_regex(cls.ip_regex), value))
@classmethod
def is_number(cls, value):
return bool(
cls.is_integer(value) or
re.match(cls._format_regex(cls.fraction_regex), value)
)
@classmethod
def is_integer(cls, value):
return bool(re.match(cls._format_regex(cls.int_regex), value))
@classmethod
def is_date(cls, value):
return bool(re.match(cls._format_regex(cls.date_regex), value))
@classmethod
def is_time(cls, value):
return bool(re.match(cls._format_regex(cls.time_regex), value))
@classmethod
def is_datetime(cls, value):
return bool(re.match(cls._format_regex(cls.datetime_regex), value))
class PrivacyFilter:
filter_string = '[FILTERED]'
email_string = '[EMAIL]'
phone_string = '[PHONE]'
preserve_phone_country_code = False
preserve_email_hostname = False
partially_preserve_email_username = False
mail_regex = r'\b({})({})\b'.format(
Validations.email_name_regex, '@' + Validations.host_regex
)
local_phone_regex = r'\b({})\b'.format(Validations.local_phone_regex)
- international_phone_regex = '\b({})\b'.format(
+ international_phone_regex = r'([^\w\d\+])({})\b'.format(
Validations.international_phone_regex
)
def __init__(self, text):
self.unfiltered = text
def filtered(self):
return self.filter_phone(self.filter_mail(self.unfiltered))
def filter_mail(self, text):
return re.sub(self.mail_regex, self.mail_replace, text)
def mail_replace(self, match_object):
if self.partially_preserve_email_username:
name = self.filter_string
if len(match_object.group(1)) >= 6:
name = match_object.group(1)[0:3] + name
return name + match_object.group(2)
elif self.preserve_email_hostname:
return self.filter_string + match_object.group(2)
else:
return self.email_string
def filter_phone(self, text):
return re.sub(
- self.international_phone_regex,
- self.phone_replace,
- re.sub(self.local_phone_regex, self.phone_string, text)
+ self.local_phone_regex,
+ self.phone_string,
+ re.sub(
+ self.international_phone_regex,
+ self.phone_replace,
+ text
+ )
)
def phone_replace(self, match_object):
if not self.preserve_phone_country_code:
return self.phone_string
- return self.phone_string
+ return match_object.group(1) + re.match(
+ r'(?:00|\+)[1-9]\d{,2}',
+ match_object.group(2)
+ ).group(0) + ' ' + self.filter_string
+