gpt4 book ai didi

python - 在 Python 中使用 re.findall() 返回所有重叠模式?

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:18 24 4
gpt4 key购买 nike

预先感谢您的阅读。

我有一个字符串:

A = "a levels"

我想匹配 A level 的以下所有可能变体:

Pattern = r"a level|a levels"

(此图案的形式已定,无法更改。)经过搜索,我希望得到:

["a level","a levels"]

我使用 findall 如下:

B = re.findall(Pattern,A)

并得到:

B = "a level"

re.findall 仅匹配第一个术语并忽略第二个重叠术语。

每:Python regex find all overlapping matches?我尝试使用:

B = re.findall(Pattern,A,overlapped = True)

并出现以下错误:

TypeError: findall() got an unexpected keyword argument 'overlapped'

显然overlapped不再作为关键字参数存在...

然后我看了这个问题:Python regex find all overlapping matches?并尝试过:

C = re.finditer(Pattern,A)
results = match.group()

results = "a level"

所以没有更好。

如何获得我想要的输出?

相关曲:How to find overlapping matches with a regexp?

最佳答案

如果所有可能的模式都与您所显示的类似,那么这可能适合您:

B=[b for pat in Pattern.split('|') for b in re.findall(pat, A)]

当然,这并不能概括为模式是一组简单的替代方案。

关于python - 在 Python 中使用 re.findall() 返回所有重叠模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41045008/

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