[英]regex multiline matching in python
我想过滤“这里是一个样本”以及之后的所有行,直到2 个新行:
这是我的文件(您可以将其用作日志文件):
here is a sample text
random line1
here is a sample text
random line2
random line3
random line4
should not match
random line 6
here is a sample
random line 5
我试过了:
\r?\n?(here is a sample).*\r?\n?(.*)
这样,如果我再次执行最后一部分'\r?\n?(.*)' ,我只会过滤下一行,我会得到另一行..
我的问题。 我需要什么正则表达式才能匹配所有行,直到我看到 2 个新行。
如果你想匹配所有直到你有 2 个换行符,但如果没有 2 个换行符也想匹配最后一次出现:
^here is a sample.*(?:\n(?!\n).*)*
模式匹配:
^
字符串开头here is a sample.*
匹配字面意思和该行的 rest(?:
非捕获组作为一个整体重复
\n(?!\n)
匹配一个换行符,并断言它后面不直接跟一个换行符.*
匹配线的rest)*
关闭非捕获组并选择性地重复它如果应该存在 2 个换行符,您可以为要保留的部分使用捕获组,并匹配 2 个换行符以确保它们存在。
^(here is a sample.*(?:\n(?!\n).*)*)\n\n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.