我需要编写 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。
我该如何解决这个问题?
最佳答案
您将需要前瞻:
^ # 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
关于Python:使用 re.match 检查字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46309007/