zpetricevic
zpetricevic

Reputation: 33

Multiline search in txt file with python

I have txt with patterns like this:

...
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".

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.

Upvotes: 0

Views: 687

Answers (1)

Derlin
Derlin

Reputation: 9871

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.

Upvotes: 2

Related Questions