[英]What's the correct way to extract a regexp match in Python?
I have found two ways to extract matches in Python: 我发现了两种在Python中提取匹配项的方法:
1. 1。
def extract_matches(regexp, text):
matches = re.match(regexp, text)
if matches:
return matches.group(1)
2. 2。
def extract_matches(regexp, text):
try:
return re.findall(regexp, text)[0]
except IndexError:
return None
Which one would you suggest me to use? 您建议我使用哪一个? And do you know any other ways to do this?
您知道其他方法吗?
Thanks, Boda Cydo. 谢谢,博达·西多(Boda Cydo)。
I would more often use re.search
(which returns any match, not just one constrained to start at the beginning of the string as re.match
does!) if I'm looking for just one match, re.finditer
if I want to loop over all matches. 如果我只想查找一个匹配项,则我会更经常使用
re.search
(它返回任何匹配项,而不是像re.match
一样受约束地开始于字符串的开头!),如果我只想查找一个匹配项,则我想使用re.finditer
循环所有比赛。 Never re.findall
if I'm going after only one match though, that's wasted effort with no upside! 如果我只参加一场比赛,
re.findall
,那是浪费精力,没有上升空间!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.