backreference

Peter Hansen peter at engcorp.com
Fri Jan 10 18:52:32 CET 2003


read-the-signature at send-spam-to-dev-null.com wrote:
> 
> I'm struggling a little with backreferences in the re-module. I read the
> docs and browsed the web but didn't find a solution for my problem yet. The
> idea is simple: given a line with punctuation, separate the punction from
> the word it is 'attached' to. For example:
> 
>     "Hello, how are you today?"
> 
> would become
> 
>     "Hello , how are you today ?"
> 
> I've been strugglin' with it for about half an hour. Guess it's time to ask
> for help :) Any suggestions?

Does something like this help?

>>> re.sub(r'([^,?])(([,?]))', r'\1 \2', 'Hello, how are you?')
'Hello , how are you ?'

Not really general-purpose, but it works on the example you gave and maybe
that's as complex as you need...

No backreferences, either, I guess. ;-)

-Peter




More information about the Python-list mailing list