0
Final exercise on RegEx for Python
Guys, I need ur help :3 The final task on RegEx for Python is to write a code which insures whether a given telephone number consists of 8 numbers in total and begins with either 1, 8 or 9. My code passes 4 tests out of 5, but unfortunately the one it doesn't is closed. So I can't see what's wrong... https://code.sololearn.com/c130Cl2bcI0H/?ref=app
6 Respostas
+ 4
pattern = r"^[189]\d{7}quot;
# should do the job (^ symbolize string start, $ string end)
+ 7
David Ashton I feel you! I've been studying and practicing RegEx over the past few days because it seems like it can be very useful in certain cases(I'm working on a few web scraping projects myself that benefit from the power of RegEx)... I must say though, RegEx has the most alien-like syntax of anything I've seen in all of programming!.!.!
+ 5
You need to check length of number as well, re.match doesn't restrict user from typing any amount of numbers even tho it will match first 8 numbers only.
So you can do a check to see if length of string is 8 then proceed further .
if len(str)==8 and re.match(pattern,str):
print("Valid")
else:
print("Invalid")
+ 4
Not being crazy about regex, I did it this way 😄
n = input()
if len(n) == 8 and n.isdigit():
if n[0] == "1" or n[0] == "8" or n[0] == "9":
print("Valid")
quit()
print("Invalid")
+ 1
I didn't expect so many answers :D looks like my mistake was in NOT stating maximal quantity of digits in a number.
And again, I admire the variability of coding (especially on the example of David Ashton).
Thank you guys!
0
I did this way 🙂
import re
#your code goes here
num = input()
pattern = r"[189]\d[1-8]"
if re.match(pattern, num) and len(num) == 8:
print("Valid")
else:
print("Invalid")