我想做的是验证用户输入。标准是只允许输入数字,不允许输入字母,不允许输入 .,/?<> 等字符。
假设用户输入 1989,它将打印 true
但是,如果用户输入数字字符以外的任何字符,例如 1989a 或 a1989 等,即使一个字符也足以让函数打印 false,然后要求用户进行另一输入。
我尝试过这样的事情:
import re
def ask_number() -> None:
# prompt positive int inputs
while True:
card = input("Number: ")
# non numeric input
if re.search("![0-9]", card):
print("false")
continue
print("true")
break
ask_number()
但由于某种原因它打印出“true”。
然后我也尝试使用findall:
# non numeric input
if re.findall("![0-9]", card):
print("false")
continue
同样的结果。
然后我尝试了插入符号:
# non numeric input
if re.findall("^![0-9]", card):
print("false")
continue
还是没有效果。 看来爆炸并没有起到任何作用。我自己还没有完全掌握Python中正则表达式的使用。任何帮助将不胜感激。
全数字输入应使用的模式是
^[0-9]*$
。
更新的脚本:
def ask_number() -> None:
# prompt positive int inputs
while True:
card = input("Number: ")
# non numeric input
if not re.search('^[0-9]*$', card):
print("false")
continue
print("true")
break
ask_number()