gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:22:43 25 4
gpt4 key购买 nike

我发现了两种在 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但是,如果我只参加一场比赛,那是白费力气,没有任何好处!

关于python - 在 Python 中提取正则表达式匹配的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2418312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com