6

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

3
  • 3
    [\d]+ would have been correct, [\d+] means one charatcer thats either a number or a plus. Also remove the |s from the character class, as they are treated as just literal | Oct 15, 2016 at 0:12
  • 1
    I think you need to read a regexp tutorial. You seem to be using [] where you really want ().
    – Barmar
    Oct 15, 2016 at 0:37
  • 2
    [] looks for a single character inside. Eg: [abc] look for a, b or c. Oct 15, 2016 at 6:03

4 Answers 4

8

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

\d+ = one or more digits.

1
  • Escape sequences work inside [], so it's a digit or +.
    – Barmar
    Oct 15, 2016 at 0:36
1

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.

1

I think a general explanation about [] and + is what you need.

[] will match with a single character specified inside.
Eg: [qwe] will match with q, w or e.

If you want to enter an expression inside [], you need to use it as [^ expression].

+ will match the preceding element one or more times. Eg: qw+e matches qwe, qwwe, qwwwwe, etc...
Note: this is different from * as * matches preceding element zero or more times. i.e. qw*e matches qe as well.

\d matches with numerals. (not just 0-9, but numerals from other language scripts as well.)

0

I don't know about complexity but this is also works:

if (len(x)==10 and "789"==x[1:4]):

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.