Petr Petrov
Petr Petrov

Reputation: 4442

Python: check str using regex

I need to write func to check str. If should fit next conditions:

1) str should starts with alphabet - ^[a-zA-Z]

2) str should contains alphabet, numbers, . and - ([\w]+*.-)

3) str should ends with alphabet or number - \w$

4) length of str should be from 10 to 50

def check_login(str):
    flag = False
    if match(r'^[a-zA-Z]([\w]*.-)\w${10, 50}', str):
        flag = True
    return flag

It returns False to all combinations. I think, error in 2 condition. I know, that I can use [a-zA-Z0-9\.-]+, but it does not indicate a mandatory entry.

How can I fix that?

Upvotes: 1

Views: 102

Answers (3)

Ajax1234
Ajax1234

Reputation: 71451

You can try this regex:

import re

final_string = [''] if not re.findall("^[a-zA-Z]{1}[a-zA-Z0-9\-\.]{9,49}\d$|\w$", s) else re.findall("^[a-zA-Z]{1}[a-zA-Z0-9\-\.]{9,49}\d$|\w$", s)
if final_string[0] == s:
   #success, a match has been found.
   pass

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Straight-forward approach with re.search() function:

import re 

def check_login(s):
    return bool(re.search(r'^[a-zA-Z][a-zA-Z0-9.-]{8,48}[a-zA-Z0-9]$', s)
           and re.search(r'\.[a-zA-Z0-9]*-|-[a-zA-Z0-9]*\.', s[1:-1]))

# test cases
print(check_login('al-De.5af3asd.2'))       # True
print(check_login('3lDe.5af3asd.2'))        # False
print(check_login('al-De.5a'))              # False
print(check_login('xl-De.5a3333333333333')) # True

Upvotes: 1

Toto
Toto

Reputation: 91430

Use:

match(r'^[a-zA-Z][\w.-]{8,48}\w$', str)

If you don't want to match _:

match(r'^[a-zA-Z][a-zA-Z0-9.-]{8,48}[a-zA-Z0-9]$', str)

If you want at least one dit, one dash, one letter and one digit:

^[a-zA-Z](?=.*-)(?=.*\.)(?=.*[0-9])[a-zA-Z0-9.-]{8,48}[a-zA-Z0-9]$

Where (?=....) is a lookahead, a zero-length assertion, that makes sure we have its content in the string.

Upvotes: 1

Related Questions