I very new to Python, and fairly new to regex. (I have no Perl experience.)
I am able to use regular expressions in a way that works, but I'm not sure that my code is particularly Pythonic or consise.
For example, If I wanted to read in a text file and print out text that appears directly between the words 'foo' and 'bar' in each line (presuming this occurred one or zero times a line) I would write the following:
fileList = open(inFile, 'r')
pattern = re.compile(r'(foo)(.*)(bar)')
for line in fileList:
result = pattern.search(line)
if (result != None):
print result.groups()[1]
Is there a better way? The if
is necessary to avoid calling groups()
on None
. But I suspect there is a more concise way to obtain the matching String when there is one, without throwing errors when there isn't.
I'm not hoping for Perl-like unreadability. I just want to accomplish this common task in the commonest and simplest way.