2017-07-02 21 views
2
>>> 
>>> 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'

+3

刪除空格 –

+0

您輸入必須包含3-5位而不是6位。如果你只是從你的模式中刪除'^',它將匹配02101,如果你只是刪除'$',匹配90210.如果刪除'^'和'$'匹配90210. – MohaMad

回答

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

量詞 – overexchange

+0

@proxchange,[' +','?','*',...也是量詞](http://www.regular-expressions.info/refrepeat.html)。 – falsetru