gpt4 book ai didi

python - 正则表达式,如何匹配第 n 次出现之前的所有内容

转载 作者:行者123 更新时间:2023-12-03 09:10:36 25 4
gpt4 key购买 nike

我正在尝试从网页中获取直到第二次出现单词 matchdate 为止的所有内容。

(.*?matchdate){2} 是我正在尝试的,但这并没有达到这个目的。该页面有超过 14 个“matchdate”匹配项,我只想将所有内容都添加到第二个匹配项,然后就不再考虑其他内容了。

https://regex101.com/r/Cjyo0f/1 <--- 我保存的正则表达式。

我在这里缺少什么?

谢谢。

最佳答案

你几乎已经拥有它了! (.*?matchdate){2} 实际上是正确的。它只需要一个 re.DOTALL标记,以便点与换行符以及其他字符匹配。

这是一个有效的测试:

>>> import re

>>> s = '''First line
Second line
Third with matchdate and more
Fourth line
Fifth with matchdate and other
stuff you're
not interested in
like another matchdate
or a matchdate redux.
'''

>>> print(re.search('(.*?matchdate){2}', s, re.DOTALL).group())
First line
Second line
Third with matchdate and more
Fourth line
Fifth with matchdate

关于python - 正则表达式,如何匹配第 n 次出现之前的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42867357/

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