[英]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.