[英]What's the correct way to extract a regexp match in Python?
我發現了兩種在Python中提取匹配項的方法:
1。
def extract_matches(regexp, text):
matches = re.match(regexp, text)
if matches:
return matches.group(1)
2。
def extract_matches(regexp, text):
try:
return re.findall(regexp, text)[0]
except IndexError:
return None
您建議我使用哪一個? 您知道其他方法嗎?
謝謝,博達·西多(Boda Cydo)。
如果我只想查找一個匹配項,則我會更經常使用re.search
(它返回任何匹配項,而不是像re.match
一樣受約束地開始於字符串的開頭!),如果我只想查找一個匹配項,則我想使用re.finditer
循環所有比賽。 如果我只參加一場比賽, re.findall
,那是浪費精力,沒有上升空間!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.