开发者

What's the correct way to extract a regexp match in Python?

开发者 https://www.devze.com 2022-12-23 00:04 出处:网络
I have found two ways to extract matches in Python: 1. def extract_matches(regexp, text): matches = re.match(regexp, text)

I have found two ways to extract matches in Python:

1.

def extract_matches(regexp, text):
  matches = re.match(regexp, text)
  if matches:
    return matches.group(1)

2.

def extract_matches(regexp, text):
  tr开发者_StackOverflow中文版y:
    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.


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. Never re.findall if I'm going after only one match though, that's wasted effort with no upside!

0

精彩评论

暂无评论...
验证码 换一张
取 消