python-blog-systemで、投稿内に長いURLを記入した際に、45文字目までしか表示しないように変更しました。
変更前
1 2 3 | import re def linkURLs(str): return re.sub(r'([^"]|^)(https?|ftp)(://[\w:;/.?%#&=+-]+)', r'\1<a href="\2\3?phpMyAdmin=cfc2644bd9c947213a0141747c2608b0">\2\3</a>', str) |
subの第2引数を正規表現で指定しています。
変更後
1 2 3 4 5 | import re def urlReplacer(match, limit = 45): return '<a href="%s?phpMyAdmin=cfc2644bd9c947213a0141747c2608b0" target="_blank">%s</a>' % (match.group(), match.group()[:limit] + ('...' if len(match.group()) > limit else '')) def linkURLs(str): return re.sub(r'([^"]|^)(https?|ftp)(://[\w:;/.?%#&=+-]+)', urlReplacer, str) |
subの第2引数を、コールバックで指定している。URLが45文字を超えた場合は、45文字目までで打ち切り、末尾に…を付加しています。