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

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

Към профила на Димитър Чаушев

Резултати

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

Код

import re
PHONE_PATTERN = r'(0[1-9]([0-9][' '\-\(\)]{0,2}){5,10})|((00|\+)[1-9][0-9]{0,2}[' '\-\(\)]{0,2}([0-9][' '\-\(\)]{0,2}){5,10})'
LOCAL_PHONE_PATTERN = r'0[1-9]([0-9][' '\-\(\)]{0,2}){5,10}'
INTERNATIONAL_PHONE_PATTERN = r'(00|\+)[1-9][0-9]{0,2}[' '\-\(\)]{0,2}([0-9][' '\-\(\)]{0,2}){5,10}'
EMAIL_PATTERN = r'[a-zA-Z0-9][a-zA-Z0-9\-\+\._]{0,200}@[a-zA-Z0-9][a-zA-Z0-9\-]{0,62}[a-zA-Z0-9](\.[a-zA-Z0-9][a-zA-Z0-9\-]{0,62}[a-zA-Z0-9])*\.[a-zA-Z]{2,3}'
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 filtered(self):
new_text = self.text
if self.preserve_email_hostname == False and self.partially_preserve_email_username == False:
email = matcher(EMAIL_PATTERN, new_text)
while Validations.is_email(email):
new_text = new_text.replace(email, '[EMAIL]')
email = matcher(EMAIL_PATTERN, new_text)
elif self.preserve_email_hostname == True and self.partially_preserve_email_username == False:
email = matcher(EMAIL_PATTERN, new_text)
while Validations.is_email(email):
hiphens = email.index('@')
filtered_email = '[FILTERED]' + email[hiphens:len(email)]
new_text = new_text.replace(email, filtered_email)
email = matcher(EMAIL_PATTERN, new_text)
elif (self.preserve_email_hostname == False or self.preserve_email_hostname == True) and self.partially_preserve_email_username == True:
email = matcher(EMAIL_PATTERN, new_text)
while Validations.is_email(email):
hiphens = email.index('@')
mail_name = email[0:hiphens]
if len(mail_name) < 6:
new_text = new_text.replace(email, '[FILTERED]' + email[hiphens:len(email)])
email = matcher(EMAIL_PATTERN, new_text)
else:
new_mail = mail_name[0:3] + '[FILTERED]' + email[hiphens:len(email)]
new_text = new_text.replace(email, new_mail)
email = matcher(EMAIL_PATTERN, new_text)
if self.preserve_phone_country_code == False:
phone = matcher(PHONE_PATTERN, self.text)
while Validations.is_phone(phone):
new_text = new_text.replace(phone, '[PHONE]')
phone = matcher(PHONE_PATTERN, new_text)
else:
phone = matcher(INTERNATIONAL_PHONE_PATTERN, new_text)
while Validations.is_phone(phone):
country_code = matcher(r'(00|\+)[1-9][0-9]{0,2}', phone)
filtered_phone = country_code + " [FILTERED]"
new_text = new_text.replace(phone, filtered_phone)
phone = matcher(INTERNATIONAL_PHONE_PATTERN, new_text)
phone = matcher(LOCAL_PHONE_PATTERN, self.text)
while Validations.is_phone(phone):
new_text = new_text.replace(phone, '[PHONE]')
phone = matcher(LOCAL_PHONE_PATTERN, new_text)
return new_text
def matcher(regex, string):
match = re.search(regex, string)
if match is None: return string
start, end = match.span()
return string[start:end]
class Validations:
@staticmethod
def is_email(value):
try:
name = re.split('@', value)[0] + "@"
hostname = re.split('@', value)[1]
except:
return False
#print(name)
#print(hostname)
return re.match(r"^[a-zA-Z0-9][a-zA-Z0-9\-\+\._]{0,200}@$", name) != None and Validations.is_hostname(hostname) == True
@staticmethod
def is_phone(value):
#local phone
if re.match(r"^0[1-9]([0-9][' '\-\(\)]{0,2}){5,10}$", value) != None:
return True
#international phone
return re.match(r"(00|\+)[1-9][0-9]{0,2}[' '\-\(\)]{0,2}([0-9][' '\-\(\)]{0,2}){5,10}", value) != None
@staticmethod
def is_hostname(value):
return re.match(r"^[a-zA-Z0-9][a-zA-Z0-9\-]{0,62}[a-zA-Z0-9](\.[a-zA-Z0-9][a-zA-Z0-9\-]{0,62}[a-zA-Z0-9])*\.[a-zA-Z]{2,3}$", value) != None
@staticmethod
def is_ip_address(value):
return re.match(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$", value) != None
@staticmethod
def is_number(value):
return re.match(r"^\-{0,1}(0\.[0-9]*|[1-9][0-9]*\.{0,1}[0-9]*)$", value) != None
@staticmethod
def is_integer(value):
return re.match(r"^\-{0,1}(0|[1-9][0-9]*)$", value) != None
@staticmethod
def is_date(value):
return re.match(r"^[1-9][0-9]{0,3}\-(0[1-9]|1[0-2])\-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$", value) != None
@staticmethod
def is_time(value):
return re.match(r"^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$", value) != None
@staticmethod
def is_datetime(value):
try:
splitted = re.split(' |T', value)
while ' ' in splitted:
splitted.remove(' ')
while '' in splitted:
splitted.remove('')
date = splitted[0]
time = splitted[1]
except:
return False
return Validations.is_date(date) and Validations.is_time(time)

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

...FF..F.FF...F.F.....FF..FF.F..F..F...
======================================================================
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-1lk2whi/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-1lk2whi/test.py", line 86, in test_does_not_filter_invalid_phone_numbers
    self.assertEqual(filtered, solution.PrivacyFilter(text).filtered())
AssertionError: '+1555 123, 55555' != '[PHONE]'
- +1555 123, 55555
+ [PHONE]


======================================================================
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-1lk2whi/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-1lk2whi/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] 2 or...'
-  [PHONE] or...
+  [PHONE] 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-1lk2whi/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: 0025(55) 12 12255'
- Phone: 0025 [FILTERED]
+ Phone: 0025(55) 12 12255


======================================================================
FAIL: test_allows_zero_years_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-1lk2whi/test.py", line 243, in test_allows_zero_years_in_date_validation
    self.assertTrue(solution.Validations.is_date('0000-01-01'))
AssertionError: False 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-1lk2whi/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-1lk2whi/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-1lk2whi/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-1lk2whi/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-1lk2whi/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_IP_addresses (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-1lk2whi/test.py", line 184, in test_validates_IP_addresses
    self.assertFalse(solution.Validations.is_ip_address('300.2.3.4'))
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-1lk2whi/test.py", line 169, in test_validates_hostnames
    self.assertTrue(solution.Validations.is_hostname('1.2.3.4.xip.io'))
AssertionError: False is not true

======================================================================
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-1lk2whi/test.py", line 204, in test_validates_more_complex_numbers
    self.assertTrue(solution.Validations.is_number('0'))
AssertionError: False is not true

----------------------------------------------------------------------
Ran 39 tests in 0.052s

FAILED (failures=14)

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

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

+import re
+
+PHONE_PATTERN = r'(0[1-9]([0-9][' '\-\(\)]{0,2}){5,10})|((00|\+)[1-9][0-9]{0,2}[' '\-\(\)]{0,2}([0-9][' '\-\(\)]{0,2}){5,10})'
+LOCAL_PHONE_PATTERN = r'0[1-9]([0-9][' '\-\(\)]{0,2}){5,10}'
+INTERNATIONAL_PHONE_PATTERN = r'(00|\+)[1-9][0-9]{0,2}[' '\-\(\)]{0,2}([0-9][' '\-\(\)]{0,2}){5,10}'
+EMAIL_PATTERN = r'[a-zA-Z0-9][a-zA-Z0-9\-\+\._]{0,200}@[a-zA-Z0-9][a-zA-Z0-9\-]{0,62}[a-zA-Z0-9](\.[a-zA-Z0-9][a-zA-Z0-9\-]{0,62}[a-zA-Z0-9])*\.[a-zA-Z]{2,3}'
+
+
+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 filtered(self):
+ new_text = self.text
+
+ if self.preserve_email_hostname == False and self.partially_preserve_email_username == False:
+ email = matcher(EMAIL_PATTERN, new_text)
+ while Validations.is_email(email):
+ new_text = new_text.replace(email, '[EMAIL]')
+ email = matcher(EMAIL_PATTERN, new_text)
+ elif self.preserve_email_hostname == True and self.partially_preserve_email_username == False:
+ email = matcher(EMAIL_PATTERN, new_text)
+ while Validations.is_email(email):
+ hiphens = email.index('@')
+ filtered_email = '[FILTERED]' + email[hiphens:len(email)]
+ new_text = new_text.replace(email, filtered_email)
+ email = matcher(EMAIL_PATTERN, new_text)
+ elif self.preserve_email_hostname == False and self.partially_preserve_email_username == True:
+ email = matcher(EMAIL_PATTERN, new_text)
+ while Validations.is_email(email):
+ hiphens = email.index('@')
+ mail_name = email[0:hiphens]
+ if len(mail_name) < 6:
+ new_text = new_text.replace(email, '[FILTERED]' + email[hiphens:len(email)])
+ email = matcher(EMAIL_PATTERN, new_text)
+ else:
+ new_mail = mail_name[0:3] + '[FILTERED]' + email[hiphens:len(email)]
+ new_text = new_text.replace(email, new_mail)
+ email = matcher(EMAIL_PATTERN, new_text)
+
+
+ if self.preserve_phone_country_code == False:
+ phone = matcher(PHONE_PATTERN, self.text)
+ while Validations.is_phone(phone):
+ new_text = new_text.replace(phone, '[PHONE]')
+ phone = matcher(PHONE_PATTERN, new_text)
+ else:
+ phone = matcher(INTERNATIONAL_PHONE_PATTERN, new_text)
+ while Validations.is_phone(phone):
+ country_code = matcher(r'(00|\+)[1-9][0-9]{0,2}', phone)
+ filtered_phone = country_code + " [FILTERED]"
+ new_text = new_text.replace(phone, filtered_phone)
+ phone = matcher(INTERNATIONAL_PHONE_PATTERN, new_text)
+
+ phone = matcher(LOCAL_PHONE_PATTERN, self.text)
+ while Validations.is_phone(phone):
+ new_text = new_text.replace(phone, '[PHONE]')
+ phone = matcher(LOCAL_PHONE_PATTERN, new_text)
+
+
+ return new_text
+
+def matcher(regex, string):
+ match = re.search(regex, string)
+ if match is None: return string
+ start, end = match.span()
+ return string[start:end]
+
+
+class Validations:
+ @staticmethod
+ def is_email(value):
+ try:
+ name = re.split('@', value)[0] + "@"
+ hostname = re.split('@', value)[1]
+ except:
+ return False
+ #print(name)
+ #print(hostname)
+ if re.match("^[a-zA-Z0-9][a-zA-Z0-9\-\+\._]{0,200}@$", name) != None and Validations.is_hostname(hostname) == True:
+ return True
+ return False
+
+ @staticmethod
+ def is_phone(value):
+ #local phone
+ if re.match("^0[1-9]([0-9][' '\-\(\)]{0,2}){5,10}$", value) != None:
+ return True
+ #international phone
+ if re.match("^(00|\+)[1-9][0-9]{0,2}[' '\-\(\)]{0,2}([0-9][' '\-\(\)]{0,2}){5,10}$", value) != None:
+ return True
+ return False
+
+ @staticmethod
+ def is_hostname(value):
+ if re.match("^[a-zA-Z0-9][a-zA-Z0-9\-]{0,62}[a-zA-Z0-9](\.[a-zA-Z0-9][a-zA-Z0-9\-]{0,62}[a-zA-Z0-9])*\.[a-zA-Z]{2,3}$", value) != None:
+ return True
+ return False
+
+ @staticmethod
+ def is_ip_address(value):
+ if re.match("^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$", value) != None:
+ return True
+ return False
+
+ @staticmethod
+ def is_number(value):
+ if re.match("^\-{0,1}(0\.[0-9]*|[1-9][0-9]*\.{0,1}[0-9]*)$", value) != None:
+ return True
+ return False
+
+ @staticmethod
+ def is_integer(value):
+ if re.match("^\-{0,1}(0|[1-9][0-9]*)$", value) != None:
+ return True
+ return False
+
+ @staticmethod
+ def is_date(value):
+ if re.match("^[1-9][0-9]{0,3}\-(0[1-9]|1[0-2])\-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$", value) != None:
+ return True
+ return False
+
+ @staticmethod
+ def is_time(value):
+ if re.match("^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$", value) != None:
+ return True
+ return False
+
+ @staticmethod
+ def is_datetime(value):
+ try:
+ splitted = re.split(' |T', value)
+ while ' ' in splitted:
+ splitted.remove(' ')
+ while '' in splitted:
+ splitted.remove('')
+ date = splitted[0]
+ time = splitted[1]
+ except:
+ return False
+ if Validations.is_date(date) and Validations.is_time(time):
+ return True
+ return False
  • Регулярните ти изрази са безумно дълги. Погледни re.VERBOSE
  • Освен това някои от тях не са raw string-ове
  • Използвай \b за разни неща
  • Опрости кода на метода filtered.
  • Този израз:

    if re.match("^...$", value) != None:
        return True
    return False
    

Не ти ли напомня на този известен нон-сенс?

  if True:
      return True
  else
      return False

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

import re
PHONE_PATTERN = r'(0[1-9]([0-9][' '\-\(\)]{0,2}){5,10})|((00|\+)[1-9][0-9]{0,2}[' '\-\(\)]{0,2}([0-9][' '\-\(\)]{0,2}){5,10})'
LOCAL_PHONE_PATTERN = r'0[1-9]([0-9][' '\-\(\)]{0,2}){5,10}'
INTERNATIONAL_PHONE_PATTERN = r'(00|\+)[1-9][0-9]{0,2}[' '\-\(\)]{0,2}([0-9][' '\-\(\)]{0,2}){5,10}'
EMAIL_PATTERN = r'[a-zA-Z0-9][a-zA-Z0-9\-\+\._]{0,200}@[a-zA-Z0-9][a-zA-Z0-9\-]{0,62}[a-zA-Z0-9](\.[a-zA-Z0-9][a-zA-Z0-9\-]{0,62}[a-zA-Z0-9])*\.[a-zA-Z]{2,3}'
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 filtered(self):
new_text = self.text
if self.preserve_email_hostname == False and self.partially_preserve_email_username == False:
email = matcher(EMAIL_PATTERN, new_text)
while Validations.is_email(email):
new_text = new_text.replace(email, '[EMAIL]')
email = matcher(EMAIL_PATTERN, new_text)
elif self.preserve_email_hostname == True and self.partially_preserve_email_username == False:
email = matcher(EMAIL_PATTERN, new_text)
while Validations.is_email(email):
hiphens = email.index('@')
filtered_email = '[FILTERED]' + email[hiphens:len(email)]
new_text = new_text.replace(email, filtered_email)
email = matcher(EMAIL_PATTERN, new_text)
- elif self.preserve_email_hostname == False and self.partially_preserve_email_username == True:
+ elif (self.preserve_email_hostname == False or self.preserve_email_hostname == True) and self.partially_preserve_email_username == True:
email = matcher(EMAIL_PATTERN, new_text)
while Validations.is_email(email):
hiphens = email.index('@')
mail_name = email[0:hiphens]
if len(mail_name) < 6:
new_text = new_text.replace(email, '[FILTERED]' + email[hiphens:len(email)])
email = matcher(EMAIL_PATTERN, new_text)
else:
new_mail = mail_name[0:3] + '[FILTERED]' + email[hiphens:len(email)]
new_text = new_text.replace(email, new_mail)
email = matcher(EMAIL_PATTERN, new_text)
-
if self.preserve_phone_country_code == False:
phone = matcher(PHONE_PATTERN, self.text)
while Validations.is_phone(phone):
new_text = new_text.replace(phone, '[PHONE]')
phone = matcher(PHONE_PATTERN, new_text)
else:
phone = matcher(INTERNATIONAL_PHONE_PATTERN, new_text)
while Validations.is_phone(phone):
country_code = matcher(r'(00|\+)[1-9][0-9]{0,2}', phone)
filtered_phone = country_code + " [FILTERED]"
new_text = new_text.replace(phone, filtered_phone)
phone = matcher(INTERNATIONAL_PHONE_PATTERN, new_text)
phone = matcher(LOCAL_PHONE_PATTERN, self.text)
while Validations.is_phone(phone):
new_text = new_text.replace(phone, '[PHONE]')
phone = matcher(LOCAL_PHONE_PATTERN, new_text)
-
return new_text
+
def matcher(regex, string):
match = re.search(regex, string)
if match is None: return string
start, end = match.span()
return string[start:end]
class Validations:
@staticmethod
def is_email(value):
try:
name = re.split('@', value)[0] + "@"
hostname = re.split('@', value)[1]
except:
return False
#print(name)
#print(hostname)
- if re.match("^[a-zA-Z0-9][a-zA-Z0-9\-\+\._]{0,200}@$", name) != None and Validations.is_hostname(hostname) == True:
- return True
- return False
+ return re.match(r"^[a-zA-Z0-9][a-zA-Z0-9\-\+\._]{0,200}@$", name) != None and Validations.is_hostname(hostname) == True
@staticmethod
def is_phone(value):
#local phone
- if re.match("^0[1-9]([0-9][' '\-\(\)]{0,2}){5,10}$", value) != None:
+ if re.match(r"^0[1-9]([0-9][' '\-\(\)]{0,2}){5,10}$", value) != None:
return True
#international phone
- if re.match("^(00|\+)[1-9][0-9]{0,2}[' '\-\(\)]{0,2}([0-9][' '\-\(\)]{0,2}){5,10}$", value) != None:
- return True
- return False
-
+ return re.match(r"(00|\+)[1-9][0-9]{0,2}[' '\-\(\)]{0,2}([0-9][' '\-\(\)]{0,2}){5,10}", value) != None
+
@staticmethod
def is_hostname(value):
- if re.match("^[a-zA-Z0-9][a-zA-Z0-9\-]{0,62}[a-zA-Z0-9](\.[a-zA-Z0-9][a-zA-Z0-9\-]{0,62}[a-zA-Z0-9])*\.[a-zA-Z]{2,3}$", value) != None:
- return True
- return False
+ return re.match(r"^[a-zA-Z0-9][a-zA-Z0-9\-]{0,62}[a-zA-Z0-9](\.[a-zA-Z0-9][a-zA-Z0-9\-]{0,62}[a-zA-Z0-9])*\.[a-zA-Z]{2,3}$", value) != None
@staticmethod
def is_ip_address(value):
- if re.match("^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$", value) != None:
- return True
- return False
+ return re.match(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$", value) != None
@staticmethod
def is_number(value):
- if re.match("^\-{0,1}(0\.[0-9]*|[1-9][0-9]*\.{0,1}[0-9]*)$", value) != None:
- return True
- return False
+ return re.match(r"^\-{0,1}(0\.[0-9]*|[1-9][0-9]*\.{0,1}[0-9]*)$", value) != None
@staticmethod
def is_integer(value):
- if re.match("^\-{0,1}(0|[1-9][0-9]*)$", value) != None:
- return True
- return False
+ return re.match(r"^\-{0,1}(0|[1-9][0-9]*)$", value) != None
@staticmethod
def is_date(value):
- if re.match("^[1-9][0-9]{0,3}\-(0[1-9]|1[0-2])\-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$", value) != None:
- return True
- return False
+ return re.match(r"^[1-9][0-9]{0,3}\-(0[1-9]|1[0-2])\-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$", value) != None
@staticmethod
def is_time(value):
- if re.match("^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$", value) != None:
- return True
- return False
+ return re.match(r"^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$", value) != None
@staticmethod
def is_datetime(value):
try:
splitted = re.split(' |T', value)
while ' ' in splitted:
splitted.remove(' ')
while '' in splitted:
splitted.remove('')
date = splitted[0]
time = splitted[1]
except:
return False
- if Validations.is_date(date) and Validations.is_time(time):
- return True
+ return Validations.is_date(date) and Validations.is_time(time)
- return False

Мерси за коментара, но просто няма да имам възможност да го оправя на мах домашното. За първи път се сблъсквам с регулярни изрази, а на всичкото отгоре още в началото на почивните дни ми се развали лаптопа и чак днес го дадох на ремонт... Добре, че намерих един стар компютър, та малко по малко я докарах до това състояние задачата.