简体   繁体   English

在 Python 中使用正则表达式在匹配模式后打印三行

[英]print three lines after the matching pattern using regular expression in Python

Dear python community,亲爱的 Python 社区,

I want to print three lines after matching pattern in python (printing the matching line is easy, eg by using re.match(r'(. )match(. )', pattern)).我想在 python 中匹配模式后打印三行(打印匹配行很容易,例如通过使用 re.match(r'(. )match(. )', pattern))。

How to do it in python?如何在python中做到这一点? The equivalent operation can be performed using "grep -A3 "pattern" filename".可以使用 "grep -A3 "pattern" filename" 执行等效操作。

Assuming you are iterating over the lines, I would use something like this假设您正在迭代这些行,我会使用这样的东西

i = 0
for line in lines:
    if re.match(pattern, line):
        i = 4
    if i > 0:
        print line
        i -= 1

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

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