gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:35:20 28 4
gpt4 key购买 nike

我需要编写 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}
$

参见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

关于Python:使用 re.match 检查字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46309007/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com