0

Regex phone number question python course

I'm trying to understand why my code doesn't work. In the problem, it says the phone number should start with 1,8 or 9 and it should have exactly 8 digits. I couldn't understand why my code accepts less than 8 digits or more than 8 digits. https://code.sololearn.com/c2A14380a14a/#py

22nd Mar 2021, 3:59 PM
Baran Aldemir
Baran Aldemir - avatar
5 odpowiedzi
+ 1
your pattern doesn't works as you expect: pattern = r"^1|8|9\d{7}
quot; check if string start with 1 (and anything else after), contains 8 (and implicitly start by using 'match'), or ends (and implicitly start with 'match') with 9 followed by 7 digits... correct one (by using 'match') could be: pattern = r"(1|8|9)\d{7}
quot; or: pattern = r"[189]\d{7}
quot;
22nd Mar 2021, 4:05 PM
visph
visph - avatar
+ 1
Baran Aldemir , "|" metacharacter means "either or". When your string starts with 1, 8 or 9 it's true that's why it doesn't check after that.
22nd Mar 2021, 4:23 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 1
Baran Aldemir I have explained in details how your pattern work in my first post/answer here ^^
22nd Mar 2021, 4:24 PM
visph
visph - avatar
0
Baran Aldemir , change the pattern => pattern = r"^[189]\d{7}
quot;
22nd Mar 2021, 4:07 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
0
@visph @TheWhiteCat Actually I know those are the answers but I was trying to understand why without parentheses it doesn't work. In other words, what does python interpret from my code?
22nd Mar 2021, 4:15 PM
Baran Aldemir
Baran Aldemir - avatar