tags:

views:

72

answers:

1

I want to add a href links to all words prefixed with # or ! or @ If this is the text

Check the #bamboo and contact @Fred re #bamboo #garden

should be converted to:

Check the <a href="/what/bamboo">#bamboo</a> and contact <a href="/who/fred">@Fred</a> re <a href="/what/bamboo">#bamboo</a> <a href="/what/garden">#garden</a>

Note that # and @ go to different places.

This is as far as I have got, just doing the hashes...

matched = re.sub("[#](?P<keyword>\w+)", \
    '<a href="/what/(?P=keyword)">(?P=keyword)</a>', \
    text)

Any re gurus able to point me in the right direction. Do I need to do separate matches for each symbol?

+4  A: 

I'd do it with a single match and a function picking the "place". I.e.:

import re

places = {'#': 'what',
          '@': 'who',
          '!': 'why',
         }

def replace(m):
  all = m.group(0)
  first, rest = all[0], all[1:]
  return '<a href="/%s/%s">%s</a>' % (
    places[first], rest, all)

markedup = re.sub(r'[#!@]\w+', replace, text)
Alex Martelli
That works perfectly. Thanks so much!
@phoebebright, you're welcome!
Alex Martelli