我是python扩展Regex的新手。我试图做一个迷你python项目,我遇到了一个问题。我在试着做电话号码检查。如果你输入一个适当的号码,你会收到一个“谢谢”,但如果你输入随机号码(不是电话号码)或随机字母,那么你应该收到一个‘再试’。
问题是,如果我输入一个字母,那么我会收到一个AttributeError:'NoneType‘对象没有属性’‘。
我怎样才能解决这个问题?任何帮助都会很好!谢谢你花时间看这个。
巴斯丁:https://pastebin.com/VzWMDgiU
代码:
import re
import time
print('Welcome, you have won 1 million dollars! Please verify your phone number!')
time.sleep(2)#sleep
content = input('Please enter your number:')
numberRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
result = numberRegex.search(content)
result.group()
time.sleep(3)#sleep
if result.group() == content:
print('thank you')
if result.group() != content:
print('try again')发布于 2021-07-21 16:18:16
这是一个解决办法:
import re
import time
print('Welcome, you have won 1 million dollars! Please verify your phone number!')
time.sleep(2) #sleep
content = input('Please enter your number:')
# content = "111-111-1111"
numberRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
result = numberRegex.search(content)
if result is not None:
time.sleep(3) #sleep
if result.group() == content:
print('thank you')
if result.group() != content:
print('try again')
else:
print('try again')另一种解决方案是尝试/捕捉块处理异常。
我猜它永远不会到达代码的这一部分:
if result.group() != content:
print('try again')但我暂时不知道,因为我不太熟悉python的regex库
发布于 2021-07-22 03:49:51
这是一个辅助的或外围的答案.
根据你的问题,我假设你对你所使用的工具有一定程度的理解,所以我认为以下几点可能对你有很大的帮助。
Regex已经很难阅读了,我建议通过为重复使用模式来使它更容易阅读。
而不是使用模式
numberRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')如果您确定某个特定数字的实例数会被重复,为什么不使用:
numberRegex = re.compile(r'\d{3}-\d{3}-\d{4}')模式\d{n}意味着regex将寻找一个重复n时间的数字\d。
和另一个
为了补充其他人的答案,为了让您更深入地了解,我认为您所遇到的错误类型的术语是语义错误。您的程序正在做它应该做的事情,但是您可能对regex函数/方法的工作方式缺乏洞察力,这就是为什么您没有“捕获”在实际输入与预期输入不同时生成的异常错误。
PS。当您在使用Python时,请尝试查看Python的命名约定,而不是numberRegex,为什么不使用number_regex。来源
https://stackoverflow.com/questions/68472970
复制相似问题