regular expression: perl ==> python

Steven Bethard steven.bethard at gmail.com
Wed Dec 22 06:48:41 CET 2004


les_ander at yahoo.com wrote:
> 
> 1) In perl:
> $line = "The food is under the bar in the barn.";
> if ( $line =~ /foo(.*)bar/ ) { print "got <$1>\n"; }
> 
> in python, I don't know how I can do this?

I don't know Perl very well, but I believe this is more or less the 
equivalent:

 >>> import re
 >>> line = "The food is under the bar in the barn."
 >>> matcher = re.compile(r'foo(.*)bar')
 >>> match = matcher.search(line)
 >>> print 'got <%s>' % match.group(1)
got <d is under the bar in the >

Of course, you can do this in fewer lines if you like:

 >>> print 'got <%s>' % re.search(r'foo(.*bar)', line).group(1)
got <d is under the bar in the bar>

Steve



More information about the Python-list mailing list