Reputation: 33
I am new to python extension Regex. I was trying to make a mini python Regex project and I ran in to a problem. I was trying to make a phone number checker. If you enter a proper number you will receive a 'thank you', but if you enter random number (not a phone number) or a random letter then you should receive a 'Try again'.
The problem is that if I enter a letter then I receive a AttributeError: 'NoneType' object has no attribute 'group.'
How can I fix the problem ? Any help would be nice! thank you for your time reading this.
Pastebin: https://pastebin.com/VzWMDgiU
The code:
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')
Upvotes: 1
Views: 79
Reputation: 297
This is an auxiliary or peripheral answer.
Based from your question I'm assuming a particular level of understanding that you have with the tools that you use, so I assume the following might be of great help to you.
Regex is already hard to read, I recommend making it a little bit more easier to read by using patterns for repeats.
Instead of using the pattern
numberRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
And if you're certain with the number of instances a particular digit would be repeated, why not use:
numberRegex = re.compile(r'\d{3}-\d{3}-\d{4}')
The pattern \d{n}
means that regex would be looking for a digit \d
that is repeated n times.
And another one
To add on other's answers, for you to look more into perhaps, I think the term for the kind of error you were experiencing is semantic error. Your program was doing what it was supposed to do, but perhaps you lacked insight on how regex functions/methods works that's why you haven't "catched" exception errors generated when the actual input is different from the expected input.
PS.
While you're at it, try to look into Python's naming convention as well
Instead of numberRegex
, why not number_regex
. source
Upvotes: 0
Reputation: 1176
This is a solution:
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')
Another solution would be a try/catch block handling the exception.
I'm guessing it never gets to this part of the code:
if result.group() != content:
print('try again')
but I left it in for now since I'm not really familiar with python's regex library
Upvotes: 1