正規表現
正規表現を使う場合は、先頭に import re と記述し正規表現モジュールをインポートする。
URL自動リンク
通常版はURL全体を表示します。長いURLは末尾省略は、45文字目以上のURLは末尾に…をつけて省略します。
通常版
1 2 | def linkURLs(str): return re.sub(r'([^"]|^)(https?|ftp)(://[\w:;/.?%#&=+-]+)', r'\1<a href="\2\3?phpMyAdmin=cfc2644bd9c947213a0141747c2608b0">\2\3</a>', str) |
長いURLは末尾省略
1 2 3 4 | def linkURLs(str): return re.sub(r'([^"]|^)(https?|ftp)(://[\w:;/.?%#&=+-]+)', urlReplacer, str) 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 '')) |
ハイフンで始まる行をLIタグで囲む
複数の行に対して、行末行頭処理をするためにはMULTILINEオプションが必要。MULTILINEオプションを使うためには、re.compilleを使う。
1 2 | def replaceLists(str): return re.sub(re.compile('^-(.+)$', re.MULTILINE), r'<li>\1</li>', str) |