繁体   English   中英

正则表达式,如何匹配所有出现的事件

[英]Regex, how to match everything up to nth occurrence

我正在尝试从网页中获取所有信息,直到第二次出现单词matchdate

(.*?matchdate){2}是我正在尝试的方法,但这并不是在做这个技巧。 该页面具有14个以上的“ matchdate”匹配项,我只想让所有内容都达到第二个,然后就别无其他。

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

我在这里想念什么?

谢谢。

您可以通过以下几种方法执行此操作:

如果可以,请删除g标志

没有全局标志,正则表达式将仅捕获其遇到的第一个实例。

https://regex101.com/r/Cjyo0f/2

在正则表达式的前面添加^

尖号将迫使正则表达式从字符串的开头开始匹配,排除所有其他可能性。

https://regex101.com/r/Cjyo0f/3

如果Python可用,请使用.split().join()

如果有常规的python,我建议:

string = "I like to matchdate, I want to each matchdate for breakfest"
print "matchdate".join(string.split("matchdate")[:2])

你差点就吃了! (.*?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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM