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