Regural expression puzzle for gurus

Joonas Paalasmaa joonas.paalasmaa at nokia.com
Fri Jul 13 09:31:34 CEST 2001


Pekka Niiranen wrote:
> 
> I have a string in the middle of a text starting with #-sign and ending
> to \W.
> I can find it with re.compile('#\w+') and  would like to replace it by
> adding a
> # -sign also to the end of it.
> 
> Example:
> 
>             original string:           xx:yy:#AAA.!:-#BBB:2324:#CCC:!"¤%
> 
>             after replacement:    xx:yy:#AAA#.!:-#BBB#:2324:#CCC#:!"¤%
> 
> How can I do replacement with a single regural expression line ?
> 
> I have found a solution like:
>            text = 'xx:yy:#AAA:-#BBB:aa'
>            line = re.compile('#\w+')
>            list = line.findall(text)
>            for i in range(len(list)):
>                  text = text.replace(list[i],list[i]+'#')
> 
> >>>  text
> 'xx:yy:#AAA#:-#BBB#:aa'
> 
> I would like to do this without the for -loop (unless somebody can
> convince
> me the found solution is the fastest available)

Try this.

import re
text = """xx:yy:#AAA.!:-#BBB:2324:#CCC:!"¤%"""
print re.sub(r"(#\w+)(\W)", r"\1#\2", text)

- Joonas



More information about the Python-list mailing list