How { } quantifier works?

半世苍凉 提交于 2019-12-10 23:15:33

问题


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


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


来源:https://stackoverflow.com/questions/44867088/how-quantifier-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!