regex substitution question

Harvey Thomas hst at empolis.co.uk
Fri Jul 19 04:28:44 EDT 2002


Eric Arnold wrote
> 
> I have a question about a regex substitution.  Lets say that with the
> following string:
> 
> x11111x22222x33333x44444x
> 
> I wanted to find anything that looked like this: 'x([^x]*)x[^x]*x' and
> replace only the first group with something (say "-")
> so the first match would be:
> "x(11111)x22222x"
> which would change the line to:
> x-x22222x33333x44444x
> 
> and so on ... then the last match would be:
> "x(33333)x44444x"
> which would change the line to:
> x-x-x-x44444x
> 
> but the last "44444" would never get substituted.  What would 
> be the easiest
> way to accomplish this?
> 
> Thanks!
> Eric
> 
Use a RE with lookbehind and lookahead assertions, i.e. specify that 'x' must precede and follow the matched string, but not be part of the matched string:

>>> r=re.compile('(?<=x)[^x]*(?=x)')
>>> r.sub('-','x11111x22222x33333x44444x')
'x-x-x-x-x'
>>>

HTH

Harvey

_____________________________________________________________________
This message has been checked for all known viruses by the MessageLabs Virus Scanning Service.





More information about the Python-list mailing list