3

I'm using Python 2.7.3 I have the following function:

def is2To4Numbers(q):
    if re.match('[0-9]{2,4}',q):return True
    else: return False

I'm trying to limit the number of digits from 2 to 4. But I get these results.

>>> is2To4Numbers('1235')
True

>>> is2To4Numbers('1')
False

>>> is2To4Numbers('12345')
True

>>> is2To4Numbers('1234567890')
True

I can't seem to get the right limit. How should i solve this? Are there other ways other than using {m,n}? Or am I even using {m,n} correctly?

Franz Noel
  • 1,820
  • 2
  • 23
  • 50

2 Answers2

11

Your regex just looks for 2 to 4 digits which exist inside your larger number. Add this:

'^[0-9]{2,4}$'

It might be a lot easier to just to use the built in numeric test and add greater than and a less than check like this:

def is2To4Numbers(q):
    try:
        return 10 <= int(q) <= 9999
    except:
        return False
Jason Sperske
  • 29,816
  • 8
  • 73
  • 124
5

If you want to search for exactly 2-to-4 digits in a larger string, and hence can not use ^ and $ as part of the pattern, then you could use negative look-behind (?<!) and negative look-ahead (?!):

import re

def is2To4Numbers(q):
    return bool(re.search(r'''(?x)    # verbose mode
                              (?<!\d) # not preceded by a digit 
                              \d{2,4} # 2-to-4 digits
                              (?!\d)  # not followed by a digit
                              ''',q))

tests = ['1', '12', '123', '1234', '12345', 'foo12', '123bar']
for test in tests:
    print('{t:6} => {r}'.format(t = test, r = is2To4Numbers(test)))

yields

1      => False
12     => True
123    => True
1234   => True
12345  => False
foo12  => True
123bar => True
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • No. I'm not searching for the number. But, I'm looking for the exact match that is valid. But, this is good to know. Thanks for the `^` advice – Franz Noel Jan 04 '13 at 19:25