Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:使用re.match检查字符串_Python_Regex - Fatal编程技术网

Python:使用re.match检查字符串

Python:使用re.match检查字符串,python,regex,Python,Regex,我需要写func来检查str。如果符合下一个条件: 1) str应该以字母开头-^[a-zA-Z] 2) str可以包含字母、数字、一个和一个- 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 但这应

我需要写func来检查str。如果符合下一个条件:

1) str应该以字母开头-
^[a-zA-Z]

2) str可以包含字母、数字、一个
和一个
-

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
但这应该意味着它以字母开头,
[a-zA-Z0-9.-]
的长度大于0小于51,以
[a-zA-Z0-9]
结尾。 如何限制
-
的数量,并将长度限制写入所有表达式

我的意思是
a
-应该返回true,
qwe123
也应该返回true


我怎样才能解决这个问题?

您将需要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} 
$
请参阅。

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

.123
(以及该系列)?@CristiFati:更新了演示链接(最初链接的版本错误)。但是如果我检查一个字母符号,例如
q
,它会返回False,但应该返回true。我很挑剔,但是
\w
允许
\ucode>:)。不管怎样,回答得很好。@CristiFati:你说得对,如果这件事重要的话,你需要把它全部写出来。