2017-09-19 50 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 –