Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Regular Expression [\d+]

Tags:

python

regex

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

like image 346
srinivas kulkarni Avatar asked Sep 08 '26 13:09

srinivas kulkarni


2 Answers

[\d+] = one digit (0-9) or + character.

\d+ = one or more digits.

like image 189
Marcel Avatar answered Sep 11 '26 04:09

Marcel


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.

like image 20
cdlane Avatar answered Sep 11 '26 02:09

cdlane