在Python中提取正则表达式匹配的正确方法是什么?

bod*_*ydo 1 python regex

我发现了两种在Python中提取匹配的方法:

1.

def extract_matches(regexp, text):
  matches = re.match(regexp, text)
  if matches:
    return matches.group(1)
Run Code Online (Sandbox Code Playgroud)

2.

def extract_matches(regexp, text):
  try:
    return re.findall(regexp, text)[0]
  except IndexError:
    return None
Run Code Online (Sandbox Code Playgroud)

你建议我使用哪一个?你知道其他任何方法吗?

谢谢,Boda Cydo.

Ale*_*lli 6

我会更经常使用re.search(返回任何匹配,而不仅仅是一个限制在字符串开头的约束re.match!)如果我只想找到一个匹配,re.finditer如果我想循环所有匹配.从来没有,re.findall如果我只追求一场比赛,这是浪费的努力没有上升!