Last active
August 29, 2015 13:55
-
-
Save noskill/8783100 to your computer and use it in GitHub Desktop.
login validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import random | |
import time | |
def make_check_login_regexes(): | |
line_start= r"""^([a-zA-Z])""" | |
long_line_expr = re.compile(line_start + r""" | |
([A-Za-z0-9\.-]{0,18}) # латинские буквы, цифры, точки и минус | |
([a-zA-Z0-9]) # alphanumeric | |
$""", re.VERBOSE) | |
one_letter_line_exr = line_start + r"$" | |
return re.compile(one_letter_line_exr), re.compile(long_line_expr) | |
ONE_CHAR_REGEX, MULTI_CHAR_REGEX = make_check_login_regexes() | |
def check_login_string_with_regex(login): | |
string_length = len(login) | |
result = False | |
if string_length == 0: | |
result = False | |
elif string_length > 20: | |
result = False | |
elif string_length == 1: | |
result = ONE_CHAR_REGEX.match(login) is not None | |
else: | |
result = MULTI_CHAR_REGEX.match(login) is not None | |
return result | |
def is_ascii(s): | |
return all(ord(c) < 128 for c in s) | |
def check_login_string(login): | |
string_length = len(login) | |
result = is_ascii(login) | |
if string_length == 0: | |
result = False | |
elif string_length > 20: | |
result = False | |
elif string_length == 1: | |
result = login.isalpha() | |
else: | |
result = login[0].isalpha() | |
result = result and login[-1].isalnum() | |
if len(login) > 2: | |
result = result and all(map(lambda ch: ch.isalnum() or ch in '.-', login[1:-1])) | |
return result | |
def gen_rand_login(): | |
lenght = random.randint(1, 30) | |
return ''.join(chr(random.randint(1, 130)) for x in range(lenght)) | |
def bench_validator(validator, array): | |
start = time.monotonic() | |
for f in array: | |
validator(f) | |
end = time.monotonic() | |
print('{0} time = {1}'.format(str(validator), end - start)) | |
if __name__ == '__main__': | |
logins = [gen_rand_login() for l in range(1 << 20)] | |
bench_validator(check_login_string_with_regex, logins) | |
bench_validator(check_login_string, logins) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment