1

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

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

2) str may contains alphabet, numbers, one . and one -

3) str should ends with alphabet or number

4) length of str should be from 1 to 50

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

But it should mean that it starts with alphabet, length of [a-zA-Z0-9.-] is more than 0 and less 51 and it ends with [a-zA-Z0-9]. How can I limit quantity of . and - and write length's limit to all expression?

I mean that a - should returns true, qwe123 also true.

How can I fix that?

1 Answer 1

2

You will need lookaheads:

^                              # start of string
    (?=^[^.]*\.?[^.]*$)        # not a dot, 0+ times, a dot eventually, not a dot
    (?=^[^-]*-?[^-]*$)         # same with dash
    (?=.*[A-Za-z0-9]$)         # [A-Za-z0-9] in the end
    [A-Za-z][-.A-Za-z0-9]{,49} 
$

See a demo on regex101.com.


Which in Python might be:

import re

rx = re.compile(r'''
^                        # start of string
    (?=^[^.]*\.?[^.]*$)  # not a dot, 0+ times, a dot eventually, not a dot
    (?=^[^-]*-?[^-]*$)   # same with dash
    (?=.*[A-Za-z0-9]$)   # [A-Za-z0-9] in the end
    [A-Za-z][-.A-Za-z0-9]{,49} 
$
''', re.VERBOSE)

strings = ['qwe123', 'qwe-123', 'qwe.123', 'qwe-.-123', '123-']

def check_login(string):
    if rx.search(string):
        return True
    return False

for string in strings:
    print("String: {}, Result: {}".format(string, check_login(string)))

This yields:

String: qwe123, Result: True
String: qwe-123, Result: True
String: qwe.123, Result: True
String: qwe-.-123, Result: False
String: 123-, Result: False
Sign up to request clarification or add additional context in comments.

8 Comments

.123 (and the family) ?
@CristiFati: Updated the demo link (wrong version linked, initially).
But if I check one alphabet symbol for example q it returns False, but it should returns True
I'm being picky, but \w allows _ :). Anyway, nice answer.
@CristiFati: Right you are, one needs to write it out in full if this matters.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.