iGwok
iGwok

Reputation: 333

using regular expressions across multiple lines (DOTALL / MULTILINE)

I am using python to read a .nk file, and I am trying to use regular expressions to search for specific items in the file.

Here's an example of 1 such item inside of this .nk file:

Viewer {
 inputs 2
 frame 1073
 viewerProcess "common"
 input_process false
 name Viewer1
 xpos -8403
 ypos -39859
}

I am currently playing around with this regular expression:

viewers = re.findall("(Viewer\s{.*})", TEXT, re.DOTALL)

The problem with this is that it fails to stop at the } symbol. So the regex returns every single line in the .nk file after "Viewer\s{"

What am I missing here?

Upvotes: 0

Views: 262

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336368

iCodez has a good solution; another possible way would be to make it explicit that no braces may be part of the match by using a negated character class:

viewers = re.findall(r"(Viewer\s{[^{}]*})", TEXT, re.DOTALL)

Upvotes: 2

user2555451
user2555451

Reputation:

You need to tell Python to match non-greedily (as little as possible):

viewers = re.findall("(Viewer\s{.*?})", TEXT, re.DOTALL)
#                                 ^

Otherwise, your pattern will capture everything from the first Viewer\s{ to the last } in the file.

Upvotes: 3

Related Questions