量词如何运作?

时间:2017-07-02 02:59:04

标签: python regex python-3.x python-3.6

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

以上所有假设应该可以使用{}量词

问题:

为什么r'^\d{3, 5}$'不会搜索'90210'

1 个答案:

答案 0 :(得分:6)

{m,n}量词之间不应有空格:

>>> 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与模式不匹配,因为它有6位数字:

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