[Tutor] Variables in regular expressions

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Sat, 24 Mar 2001 20:43:57 -0800 (PST)


On Sat, 24 Mar 2001, VanL wrote:

> Hello,
> 
> Is it possible to use variables in regular expressions:  I tried
> this, but it didn't work:
> 
> >>> import re
> >>> matchstr = 'fleas'
> >>> sentence = 'my dog has fleas'
> >>> if re.match(matchstr, sentence): print "Yes, it works."
> ...
> >>>
> 
> Is this impossible to do, or am I doing it wrong?

It's possible.  Um... I mean, that it's possible to do, not that it's
possible that you're doing it wrong.  Gosh, that sounded funny.


Using variables with it should work.  However, try re.search() instead:

###
>>> import re
>>> if re.search('fleas', 'my dog has fleas'): print 'yes!'
... 
yes!
###

There's a difference between match() and search(): match() will start at
the very beginning of the thing we're searching through, and if it doesn't
match at the beginning, then it doesn't work.

search(), on the other hand, does search through the whole string to see
if it pattern-matches, and behaves the way you probably expect it to.  


For more information, take a look at:

    http://python.org/doc/current/lib/matching-searching.html

which explains in more detail why they're different from each other.

Hope this helps!