Python - How to use regexp on file, line by line, in Python


Tried to use different title for the question, but if you can improve the question, please do so.

Here is my regexp: f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)

I'd have to apply this on a file, line by line. The line by line is OK, simple reading from file, and a loop. But how do I apply the regexp to the lines?

Thanks for all the help, and sorry for the noob question.

5/31/2011 11:34:56 AM

The following expression returns a list; every entry of that list contains all matches of your regexp in the respective line.

>>> import re
>>> [re.findall(r'f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)',line) 
            for line in open('file.txt')]
5/31/2011 11:39:39 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow