Exact match digits or limit in Python Regex

I am 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 am 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 not get the correct limit. How do i solve this? Are there other ways besides using {m, n}? Or am I using {m, n} correctly?

+2
source share
2 answers

Your regular expression is simply looking for 2 to 4 digits that exist inside your larger number. Add this:

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

It would be much easier to use the built-in numerical test and add more and less than a check:

def is2To4Numbers(q):
    try:
        return 10 <= int(q) <= 9999
    except:
        return False
+8
source

2-4 , , ^ $ , (?<!) (?!):

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

1      => False
12     => True
123    => True
1234   => True
12345  => False
foo12  => True
123bar => True
+3

Source: https://habr.com/ru/post/1681665/


All Articles