overexchange
overexchange

Reputation: 1

How { } quantifier works?

>>>
>>> re.search(r'^\d{3, 5}$', '90210')  # {3, 5} 3 or 4 or 5 times
>>> re.search(r'^\d{3, 5}$', '902101')  # {3, 5} 3 or 4 or 5 times
>>> re.search(r'^\w{3, 5}$', 'hello')  # {3, 5} 3 or 4 or 5 times
>>> re.search(r'^\w{3, 5}$', 'hell')  # {3, 5} 3 or 4 or 5 times
>>>

All of the above suppose to should work, with {} quantifier


Question:

Why r'^\d{3, 5}$' does not search for '90210'?

Upvotes: 2

Views: 98

Answers (1)

falsetru
falsetru

Reputation: 369364

There should be no space between {m and , and n} quantifier:

>>> re.search(r'^\d{3, 5}$', '90210')  # with space


>>> re.search(r'^\d{3,5}$', '90210')  # without space
<_sre.SRE_Match object at 0x7fb9d6ba16b0>
>>> re.search(r'^\d{3,5}$', '90210').group()
'90210'

BTW, 902101 does not match the pattern, because it has 6 digits:

>>> re.search(r'^\d{3,5}$', '902101')

Upvotes: 6

Related Questions