gpt4 book ai didi

Python:正则表达式仅找到所搜索字符串的一部分

转载 作者:行者123 更新时间:2023-11-28 21:20:08 26 4
gpt4 key购买 nike

content 变量包含多行字符串:

content = """
/blog/1:text:Lorem ipsum dolor sit amet, consectetur ### don't need this
<break>
text:Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
<break>
text:Excepteur sint occaecat cupidatat non proident.

/blog/16:text:Other Lorem ipsum dolor ### SEEKING THIS!!!
<break>
text:Other, really other
<break>
text:Blah blah.
"""

我正在尝试使用 /blog/16 模式找到所需的事件:

re.findall('^(?ism)%s?:(.*?)(\n\n)' % '/blog/16', content)

并期待得到这个

[(u'/blog/16:text:Other Lorem ipsum dolor ### SEEKING THIS!!!
<break>
text:Other, really other
<break>
text:Blah blah.', u'\n\n')]

但得到错误的结果(/blog/1)

[(u'/blog/1:text:Lorem ipsum dolor sit amet, consectetur ### don't need this
<break>
text:Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
<break>
text:Excepteur sint occaecat cupidatat non proident.', u'\n\n')]

我的错误是什么?

最佳答案

插入博客文本后,正则表达式的这一部分:

/blog/16?:

表示“按字面意思匹配:/blog/1;然后按字面意思匹配 6(零次或一次);然后按字面意思匹配 :”。相反,请尝试:

(?ism)^/blog/16:(.*?)$

这会在行首逐字查找所有 /blog/16:,然后对任何字符进行非贪婪搜索直到行尾(即捕获其余部分行上的文字)。

您可能会找到 regex101对于开发和测试正则表达式很有用。

关于Python:正则表达式仅找到所搜索字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23307768/

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