How to improve my Python regex syntax?
Posted
by FarmBoy
on Stack Overflow
See other posts from Stack Overflow
or by FarmBoy
Published on 2010-03-29T08:45:05Z
Indexed on
2010/03/29
9:03 UTC
Read the original article
Hit count: 448
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.
© Stack Overflow or respective owner