Python Regex | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Python Regex

I am trying to match a phone number Where phone number start with 1 or 8 or 9 and total number of digits must be 8. What am i doing wrong? import re n=input() pattern=r'(1|8|9)[0-9]{7}' if(re.match(pattern,n)): print("Valid") else: print("Invalid")

11th Oct 2020, 12:41 PM
sid
sid - avatar
7 Answers
+ 2
It’s likely you need to anchor your match to the end of the string using ‘$’. This avoids matches for inputs more than 8 numbers long. Try pattern = re.match(r’(1|8|9)[0-9]{7}$’, n))
11th Oct 2020, 1:04 PM
Russ
Russ - avatar
+ 3
Jan Markus I see :) it works fine like that.
11th Oct 2020, 1:11 PM
Russ
Russ - avatar
+ 3
sid Inputs ‘123456789’ and ‘12345678hello’ are both returning ‘Valid’ which they are not.
11th Oct 2020, 1:15 PM
Russ
Russ - avatar
+ 2
Jan Markus I don’t see any difference between your code and OP’s... 🤔
11th Oct 2020, 1:06 PM
Russ
Russ - avatar
+ 2
Jan Markus, Russ Thank you for your time guyz.Really appreciated. Stay Safe.
11th Oct 2020, 3:45 PM
sid
sid - avatar
+ 1
Jan Markus no its not working
11th Oct 2020, 12:56 PM
sid
sid - avatar
+ 1
Russ it was the '
#x27;.now its passed Thank you.
11th Oct 2020, 3:44 PM
sid
sid - avatar