Karl
Karl

Reputation: 5822

Regex find contents between curly brackets across line break

Let's say I have the following string:

text="""foo: '{{ .Env.FOO
  }}'
bar: '{{ .Env.BAR }}'
foobar: {{ .Env.FOOBAR }}
"""

I can match the single-line cases easily enough with

import re
found=re.findall("{{ .Env..*?}}", text)

But how would I match the case where the }} is on the second line? I've tried the following but matches up to the final }} it finds. Something that stops at the first }} would work.

with_line_break=re.findall("{{ .Env..*?\n.*}}", text)
print(with_line_break)

Prints:

{{ .Env.FOO
  }}
{{ .Env.BAR }}'
foobar: {{ .Env.FOOBAR }}

Upvotes: 0

Views: 73

Answers (1)

user459872
user459872

Reputation: 24707

You can use the flag re.DOTALL.

re.DOTALL

Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline. Corresponds to the inline flag (?s).

found = re.findall("{{ .Env..*?}}", text, re.DOTALL)

Upvotes: 1

Related Questions