2017-09-19 55 views
1

我需要編寫func來檢查str。如果應該適合下一個條件:Python:使用re.match檢查字符串

1)STR應與字母開始 - ^[a-zA-Z]

2)乙方可以包含字母,數字,一個.和一個-

3)STR應用字母或數字結束

4)STR的長度應爲1至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 

但它SH意思是它以字母開頭,長度爲[a-zA-Z0-9.-]大於0小於51,並以[a-zA-Z0-9]結尾。 如何限制.-的數量,並將所有表達式的長度限制寫入?

我的意思是a - 應該返回true,qwe123也是如此。

我該如何解決這個問題?

回答

2

你需要向前看符號:

^        # 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} 
$ 

a demo on regex101.com


其中在 Python可能是:

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))) 

這產生了:

String: qwe123, Result: True 
String: qwe-123, Result: True 
String: qwe.123, Result: True 
String: qwe-.-123, Result: False 
String: 123-, Result: False 
+0

'.123'(和家庭)? – CristiFati

+0

@CristiFati:更新了演示鏈接(最初鏈接的版本錯誤)。 – Jan

+0

但是,如果我檢查一個字母符號,例如'q',它將返回False,但它應該返回True –