Python正則表達式返回首次匹配到的字符及查詢的健壯性


re.findall(pattern,string)會搜索所有匹配的字符,返回的是一個列表,獲取首個匹配需要re.findall(pattern,string)[0]訪問, 但是如果findall沒匹配成功則返回空列表,這時用列表下標去訪問元素時就會報IndexError: list index out of range。

如:

>>>re.findall('abc','abd')
[]
>>>re.findall('abc','abd')[0]
Traceback (most recent call last):
File "<input>", line 1, in <module>
IndexError: list index out of range

 

我們可以在pattern后面加一個"|$"來生成一個默認的''元素:

>>>re.findall('abc|$','abd')[0]
''
>>>re.findall('abc|$','abcdef') #注意,無論匹配到與否,都會附加上一個''元素
['abc', '']

 

同樣適用於re.search

>>> re.search('\d+|$', 'aa33bbb44').group()
'33'
>>> re.search('\d+|$', 'aazzzbbb').group()
''

 

如果不加|$的話:

>>>re.search('\d+', 'aazzzbbb').group() #search沒匹配上,再用.group()就會報錯
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

 

參考:https://stackoverflow.com/questions/38579725/return-string-with-first-match-regex


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM