Regexp problem

Tim Chase python.list at tim.thechases.com
Thu Jul 30 09:04:24 EDT 2009


> I have a problem and i'm not very good at regular expressions.
> I have a text like "lalala lalala tiruri beldar-is-listening tiruri
> lalala" I need a regexp to get the 'beldar' part, the format is
> 'something-is-listening', i need to get the something part, use it in
> my code, and then replace the whole 'something-is-listening' for
> another string.


Pretty easy:

   >>> import re
   >>> s = "lalala lalala tiruri beldar-is-listening tiruri lalala"
   >>> r = re.compile(r'(\w+)-is-listening')
   >>> r.search(s).group(1)
   'beldar'
   >>> r.sub('this is a replacement', s)
   'lalala lalala tiruri this is a replacement tiruri lalala'

-tkc





More information about the Python-list mailing list