0

I'm making a project and part of it is taking in a python file as a text file and parsing it using regular expressions.

I was able to use this fine (where program is a string containing the code with newlines):

findall(r"def (.*?)\((.*?)\)", program)

But this line just gives None when I expect it to give a Match object where .group() returns "func1(None, None)"

mainblock = search(r'if __name__ == "__main__":(.*?)#END', program)

An abbreviated version of the python file I'm parsing is below:

def func1(stuff, morestuff):
    pass

if __name__ == "__main__":
    func1(None, None)
#END

I've checked for any discrepencies in the regex itself and I can't find any. I also tried copy/pasting it directly from the code file and it still couldn't find a match

1 Answers1

2

You need to either include the newline characters \n in the regular expression, like this,

r'if __name__ == "__main__":\n(.*?)\n#END'

or enable the DOTALL flag, meaning that . also matches line breaks.

(MULTILINE means something else, which can be counterintuitive.)

mkrieger1
  • 19,194
  • 5
  • 54
  • 65