return 0 return 0 - 19 days ago 7
Python Question

How to match text between brackets across multiple lines in python

Say I have a file that I need to process:

names = [
joe
billy
kate
]


I want to use regex to match the string

[
joe
billy
kate
]


and remove the newline character within.

I have tried

with open('file.txt', 'r') as f:
data = f.readlines()
file = "".join(data)
search = re.search(r'= \[[^]*\]', file, re.MULTILINE)


but I get the error
sre_constants.error: unexpected end of regular expression
. I have already tried the regex on http://regexr.com/ and it worked fine. What's wrong with my python script?

EDIT:
My real problem looks like

names = [
joe[ggg]
billy[ddd]
kate[aaa]
]

Answer

You forget to close the character class.

search = re.search(r'(?s)= (\[.*?\s\])(?=\s|$)', file)

DEMO

Comments