How { } quantifier works?

2019-07-20 17:12发布

>>>
>>> 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'?

1条回答
Animai°情兽
2楼-- · 2019-07-20 17:53

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')
查看更多
登录 后发表回答