简体   繁体   English

使用python在txt文件中进行多行搜索

[英]Multiline search in txt file with python

I have txt with patterns like this: 我有这样的模式txt:

...
72 anything
73 }
74 something {
75 something2
76 something3 withVariableTextHere
77 anything
...

I've tried searching for: "something {\\nsomething2\\nsomething3)" and I do get True result with re.findall, but after I've found the pattern I want to print whole #76 line, because I need info after "something3". 我尝试搜索: "something {\\nsomething2\\nsomething3)"并通过re.findall获得了True结果,但是找到模式后,我想打印整行#76行,因为在“ something3”。

Does anyone have idea how I could do that? 有人知道我该怎么做吗? And I want to do it multiple times trough the same file, essentially whenever pattern is found I want to print whole third line. 而且我想通过同一个文件多次执行该操作,基本上,只要找到模式,我都希望打印整个第三行。

You can use capturing groups in your regex. 您可以在正则表达式中使用捕获组。 For example: 例如:

s = """anything
}
something {
something2
something3 withVariableTextHere
anything"""

re.findall("something {\nsomething2\nsomething3(.*)", s)

Will yield: 将产生:

[' withVariableTextHere']

In short, it will return everything that matches the part of the regex in parenthesis, here anything before a new line . 简而言之,它将返回括号中与正则表达式部分匹配的所有内容,这里是换行符之前的所有内容

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

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