Skip to content

Instantly share code, notes, and snippets.

@beniwohli
Created March 27, 2014 09:02
Show Gist options
  • Save beniwohli/9803349 to your computer and use it in GitHub Desktop.
Save beniwohli/9803349 to your computer and use it in GitHub Desktop.
linkify/hashtagify
# -*- coding: utf-8 -*-
import re
_linkify_re = re.compile(
r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))""")
_hashtag_re = re.compile(r'(?: |^)#(\w{2,})', re.UNICODE)
def _link_replace(match):
href = match.groups(1)[0]
if not href.startswith('http'):
href = 'http://' + href
return '<a href="%s" target="_blank">%s</a>' % (href, match.groups(1)[0])
def linkify(content):
return _linkify_re.sub(_link_replace, content)
def hashtagify(content, url_template):
def _hashtag_replace(match):
tag = match.groups(0)[0]
url = url_template % tag
# This might need escaping.
return ' <a href="%s" target="_blank">#%s</a>' % (url, tag)
return _hashtag_re.sub(_hashtag_replace, content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment