0

to solve phone number validation in python(regular expression) i use this code ,but didn't get the positive result,what's wrong

impot re a = str(input()) pattern = r"^[189][0-9]+" if re.match(pattern,a): if len(a) == 8: print("valid") else: print("invalid") else: print("invalid)

6th Jun 2021, 6:22 PM
Md Shakil
Md Shakil - avatar
4 Respostas
0
Consider a string of length 8 such as "136ghg45", it will output valid for it as your pattern matches "136" . Instead use the following pattern , import re a = input() pattern = r"[189][0-9]{7}
quot; if re.match(pattern,a): print("valid") else: print("invalid") In the above pattern, {7} will check for exact 7 occurences of number after first number which makes it a total 8 . "
quot; will check if string is ending with only 8 characters in total (so no need of checking length as an extra step). 𝗙𝗬𝗜 : Input function returns a string only . Also there was a syntax error and spelling mistake in your code that i corrected .
6th Jun 2021, 8:01 PM
Abhay
Abhay - avatar
0
It also doesn't work bro
6th Jun 2021, 9:08 PM
Md Shakil
Md Shakil - avatar
0
I've write this more simpe: import re p = r'^[189]' a = str(input()) if re.match(p,a) and len(a) == 8: print('valid') else: print('invalid')
6th Jun 2021, 9:34 PM
Ervis Meta
Ervis Meta - avatar
0
# oneliner: print("Valid" if re.fullmatch("[189].{7}", input()) else "Invalid")
6th Jun 2021, 11:20 PM
visph
visph - avatar