Regural expression puzzle for gurus
Alex Martelli
aleaxit at yahoo.com
Fri Jul 13 06:28:12 EDT 2001
More information about the Python-list mailing list
Fri Jul 13 06:28:12 EDT 2001
- Previous message (by thread): Regural expression puzzle for gurus
- Next message (by thread): Regural expression puzzle for gurus
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
"Pekka Niiranen" <krissepu at vip.fi> wrote in message news:3B4EA0C8.9F697D06 at vip.fi... > 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+') line = re.compile('(#\w+)') text = line.sub(r'\1#', text) should do what you want. The parentheses around the re's pattern define a group, the \1 in sub backreferences to the group (in many contexts "group 0" can be used to mean the whole substring matched, but, I believe, not here, so I don't think you can avoid the parentheses in the pattern). Alex
- Previous message (by thread): Regural expression puzzle for gurus
- Next message (by thread): Regural expression puzzle for gurus
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list