Python Regular Expression [\d+]

11,309

Solution 1

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

\d+ = one or more digits.

Solution 2

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.)

Solution 3

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.

Share:
11,309

Related videos on Youtube

srinivas kulkarni
Author by

srinivas kulkarni

Updated on June 04, 2022

Comments

  • srinivas kulkarni
    srinivas kulkarni almost 2 years

    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

    • Sebastian Proske
      Sebastian Proske over 7 years
      [\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 |
    • Barmar
      Barmar over 7 years
      I think you need to read a regexp tutorial. You seem to be using [] where you really want ().
    • Jithin Pavithran
      Jithin Pavithran over 7 years
      [] looks for a single character inside. Eg: [abc] look for a, b or c.
  • Barmar
    Barmar over 7 years
    Escape sequences work inside [], so it's a digit or +.

Related