我对python很陌生,显然我也不知道如何使用regex。我只是好奇是否有可能在字符串中的其他数字之前输入一个数字?
这个函数(def校验零)应该做的是检查是否在其他数字之前输入0,然后返回True (表示无效)。
import string
import re
plate_pattern = re.compile('\D*\d*')
def main():
plate = input("Plate: ")
tests = [exclusions, platecheck, checkzero]
invalid = any(test(plate) for test in tests)
if invalid:
print("Invalid \nNo numbers in the start/middle of the plate, first number may not be 0. \nNo punctuation allowed.\nPlate must be between 2-6 characters.")
else:
print("Valid")
def exclusions(s):
if any(c in string.punctuation for c in s):
return True
return len(s) > 6 or len(s) < 2
def platecheck(s):
return not plate_pattern.fullmatch(s)
def checkzero(s):
# Not sure how to go about creating the function to check if zero is inputted before other numbers.
pass
main()输入/输出示例:
输入:
test02输出:
Invalid
...输入:
test20输出:
Valid发布于 2022-06-05 01:50:07
回应意见的修订
任何点的第一个数字不能是0
您可以从字符串^的开头查看非数字字符[^\d]*,然后是0(可能后面跟着一个数字.*\d? ),然后从那里进行相同的操作(也是更新的测试用例):
def checkzero(s):
p = re.compile(r"^[^\d]*0.*\d?")
matched = re.search(p, s)
return re.search(p, s) != None
test_cases = ["test0", "test1", "test01", "test10", "test101"]
for test in test_cases:
print(test, end = ": ")
if checkzero(test):
print("Matched, INVALID")
else:
print("Not matched, VALID")```输出:
test0: Matched, INVALID
test1: Not matched, VALID
test01: Matched, INVALID
test10: Not matched, VALID
test101: Not matched, VALID原邮政
你可以用re.search()。如果找到匹配,那么将返回一个Match对象,否则将返回None。
def checkzero(s):
p = re.compile(r"0.*\d")
matched = re.search(p, s)
return re.search(p, s) != None注意:如果希望0紧跟数字,请删除regex表达式中的.*。
发布于 2022-06-05 02:05:35
因此,简单地说,我们只是检查一下,在给定字符串中第一次出现的数字是否为0。
import re
def checkzero(s):
return re.search(r'\d', s).group() == '0'测试:
test_cases = ['test0', 'test02', 'test20', 'test002', 'test2022']
for test_case in test_cases:
print(checkzero(test_case))输出:
>>> True
>>> True
>>> False
>>> True
>>> Falsehttps://stackoverflow.com/questions/72504205
复制相似问题