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

Regex not working

Sorry but my regular expression do not work as I would like and I guess it is okay (based on what I learned and what I understand). pattern = r'(^1|^8|^9)[0-9]{7}' This is my regular expression, it is supposed to validate a phone number that starts with 1, 8 or 9 and its length should be 8, but my regex takes inputs greater than 8 as valid. I can solve it by putting in the conditional that validates the phone numbers that the length of the str should be 8: if re.match (pattern, * input *) and len (* input *) == 8: But I would like to solve it with a regular expression that meets the requirement. (IDK if it is possible).

30th Mar 2021, 11:26 PM
Chepe
Chepe - avatar
1 Answer
+ 2
What worked for me was specifying that the string should end after there’s been 8 characters. $ in the end of the pattern. Hope it works
31st Mar 2021, 1:20 AM
Alexander Crum
Alexander Crum - avatar