gpt4 book ai didi

python - 正则表达式:将单词与侵入性符号匹配

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

我试图将所有“单词”与其中的干扰星号匹配,包括开头和结尾(但没有其他标点符号)。

例如,我预计下面有七场比赛。相反,我得到了两个。

text = "star *tar s*ar st*r sta* (*tar) (sta*) sta*."
p = re.compile(r"\b\w*\*+\w*\b")
p.findall(text) # ['s*ar', 'st*r']
# Expected ['*tar', 's*ar', 'st*r', 'sta*', '*tar', 'sta*', 'sta*']

我知道原因是星号不被视为由 \b 元字符界定的单词的一部分,但在阅读了所有 Python 的 How-to 之后, 我仍然不太清楚如何获得我想要的东西。

最佳答案

感谢您编辑预期的输出。

因此,除了@benvc 的出色解决方案之外,这个解决方案还考虑了递归,因此如果您希望在文本具有多个 * 时进行捕获,则将捕获整个找到的字符串并且不会忽略其他 *

#Acting on your original text string
>>> text = "star *tar s*ar st*r sta* (*tar) (sta*) sta*."
>>> re.findall('((?:[a-z\*]*(?:\*)(?:[a-z\*]*)))+', text)
['*tar', 's*ar', 'st*r', 'sta*', '*tar', 'sta*', 'sta*']



#Acting on a slightly **MORE COMPLEX** string and returning it accurately
>>> text = "*tar *tar* star s*a**r *st*r* sta* (*tar) st*r** (sta**) s*ta*."
>>> re.findall('((?:[a-z\*]*(?:\*)(?:[a-z\*]*)))+', text)
['*tar', '*tar*', 's*a**r', '*st*r*', 'sta*', '*tar', 'st*r**', 'sta**', 's*ta*']

.

如果您需要我解释它是如何工作的,请告诉我以备将来引用。

关于python - 正则表达式:将单词与侵入性符号匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55113047/

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