Python's regular expression?

Mirco Wahab peace.is.our.profession at gmx.de
Mon May 8 09:13:43 EDT 2006


Hi John

>>    import re
>>
>>    t = 'blue socks and red shoes'
>>    p = re.compile('(blue|white|red)')
>>    if p.match(t):
> 
> What do you expect when t == "green socks and red shoes"? Is it possible
> that you mean to use search() rather than match()?

This is interesting.
What's in this example the difference then between:

   import re

   t = 'blue socks and red shoes'
   if re.compile('blue|white|red').match(t):
      print t

and

   t = 'blue socks and red shoes'
   if re.search('blue|white|red', t):
      print t

> There is no need to compile the regex in advance in Python, either.
> Please consider the module-level function search() ...
> if re.search(r"blue|white|red", t):
> # also, no need for () in the regex.

Thats true. Thank you for pointing this out.
But what would be an appropriate use
of search() vs. match()? When to use what?

I answered the posting in the first place
because also I'm coming from a C/C++/Perl
background and trying to get along in Python.

Thanks,

Mirco




More information about the Python-list mailing list