gpt4 book ai didi

python - RE 的 HTML ID 值验证

转载 作者:太空宇宙 更新时间:2023-11-03 11:01:15 25 4
gpt4 key购买 nike

问题陈述:

ID value must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

我是通过正则表达式完成的。

代码:

>>> import re
>>> id_value1 = "custom-title1"
>>> id_value2 = "1-custom-title"
>>> pattern = "[A-Za-z][\-A-Za-z0-9_:\.]*"

有效ID值代码

>>> flag= False
>>> try:
... if re.finadll(pattern, id_value1)[0]==id_value1:
... flag=True
... except:
... pass
...
>>> print flag
False

无效 ID 值代码:

>>> flag = False
>>> try:
... if re.findall(pattern, id_value2)[0]==id_value2:
... flag=True
... except IndexError:
... pass
...
>>> print flag
False

IndexError 代码

>>> try:
... if re.findall(pattern, "")[0]=="":
... print "In "
... except IndexError:
... print "Exception Index Error"
...
Exception Index Error
>>>

我将在一个函数中移动上面的代码。此函数将调用超过 1000 次。那么有人可以优化上面的代码吗?

最佳答案

你应该匹配字符串的结尾,编译你的模式并使用 re.match() 而不是 re.findall()

import re
id_value1 = "custom-title1"
id_value2 = "1-custom-title"

pattern = "[A-Za-z][\-A-Za-z0-9_:\.]*$"
compiled = re.compile(pattern)

def validate(id):
return bool(compiled.match(id))

print validate(id_value1)
print validate(id_value2)

关于python - RE 的 HTML ID 值验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31808826/

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