0

(HELP) Stuck on regex exercise in Python course

As the title would suggest, I'm stuck on the exercise at the end of the regex module in the Python course. I polished off most of the module end of last week, couldn't get in on Monday, And now I've been staring at my screen for nearly two hours trying to solve this god damn exercise. As you may know, you are supposed to take a string of numbers as input and check if it's a valid phone number. A valid phone number is 8 characters long and starts with the numbers 1, 8, or 9. Checking the length was simple enough to do with the len function and some if statements, the problems started when I had to check the first character. I threw together a solution, hit run, and everything came back invalid. I've tried a whole host of different methods and done quite a bit of googling, but I still can't get something that that actually meets the requirements. I've been at this for nearly two hours and am near-totally out of ideas, So I'm turning to the community over here for help. Am I doing something wrong? Am I missing something? Whatever it is, I hope someone else can see it. In the interests of problem-solving, here is the code as it currently stands: import re phonenum = str(input) pattern = r"^[1|8|9]" if len(phonenum) == 8: if re.match(pattern, phonenum): print("Valid") else: print("Invalid") else: print("Invalid") UPDATE: It's done. thanks to everyone in the comments.

12th May 2021, 4:05 PM
James Anthony Ville
3 Antworten
+ 1
import re pattern = r"^[189]\d{7}" #added constraints phonenum = input() #by default input is string no need of str. match = re.match(pattern,phonenum) if match and len(phonenum)==8: print ("Valid") else: print ("Invalid")
12th May 2021, 4:12 PM
Aditya
Aditya - avatar
0
pattern = [1|8|9]\d{7}. your code will give valid for something like 1fh6hg56 which is wrong . So you need to check if other characters are numbers as well which is what "/d{7}" will do . Also re.match looks for the pattern at the beginning of string . So no need to use "^".
12th May 2021, 4:19 PM
Abhay
Abhay - avatar
0
I get it, thanks guys. In all seriousness, I sort of expected to hit a speedbumb going into regex. Going by what I've heard, regex doesn't have a difficulty curve so much as a difficulty mountainside when it comes to learning how to use it effectively. Still, I think I have this one in the bag.
14th May 2021, 3:12 PM
James Anthony Ville