gpt4 book ai didi

python - 在python中使用re查找关键字旁边的两个字符串

转载 作者:太空宇宙 更新时间:2023-11-03 17:13:48 25 4
gpt4 key购买 nike

我需要找到关键字旁边的两个字符串。这是一个示例字符串

\plottwo{image1}{image2}

关键字是\plottwo,正确结果是

[image1, image2]

我知道如果关键字旁边只有一个字符串我可以使用

re.findall('\plottwo.*?{(.*?)},text)

如何将其扩展为两个字符串?

最佳答案

请注意,这恰好匹配两个图像字符串:

import re

matcher = re.compile(r"""\\plottwo # The literal \plottwo
{ # Opening brace for the first image group
( # Start the first capture group
[^}]+ # Match anything OTHER than a closing brace
) # End the first capture group
} # Closing brace
{ # Opening brace for the second image group
( # Start the second capture group
[^}]+ # Match anything OTHER than a closing brace
) # End the second capture group
} # Closing brace
""", re.VERBOSE)

print matcher.findall('\\plottwo{image1}{image2}')

如果您希望捕获一个或两个图像字符串,请将捕获组之一设为可选:

import re

matcher = re.compile(r"""\\plottwo # The literal \plottwo
{ # Opening brace for the first image group
( # Start the first capture group
[^}]+ # Match anything OTHER than a closing brace
) # End the first capture group
} # Closing brace
(?: # Non-saving group that we can make optional
{ # Opening brace for the second image group
( # Start the second capture group
[^}]+ # Match anything OTHER than a closing brace
) # End the second capture group
} # Closing brace
)? # End the non-capturing group
""", re.VERBOSE)

print matcher.findall('\\plottwo{image1}{image2}')
print matcher.findall('\\plottwo{image2}')

但为了回应其中一条评论,正则表达式通常不是执行复杂解析作业(有时甚至是简单解析作业:-)的最佳方式。

关于python - 在python中使用re查找关键字旁边的两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33838289/

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