I am working on regular expression python, I came across this problem.
A valid mobile number is a ten digit number starting with a 7,8 or 9. my solution to this was :
if len(x)==10 and re.search(r'^[7|8|9]+[\d+]$',x):
for which i was getting error. later I changed it to
if len(x)==10 and re.search(r'^[7|8|9]+\d+$',x):
for which all test cases passed. I want to know what the difference between using and not using [] for \d+ in regex ?
Thanks
[\d+] = one digit (0-9) or + character.
\d+ = one or more digits.
You could also do:
if re.search(r'^[789]\d{9}$', x):
letting the regex handle the len(x)==10 part by using explicit lengths instead of unbounded repetitions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With