0

グループで置換を行う方法はありますか?

カスタム書式設定に基づいて、リンクをテキストに挿入しようとしているとします。したがって、次のようなものが与えられます。

This is a random text. This should be a [[link somewhere]]. And some more text at the end.

で終わりたい

This is a random text. This should be a <a href="/link_somewhere">link somewhere</a>. And some more text at the end.

グループ 1 として角括弧内のものと一致することはわかってい'\[\[(.*?)\]\]'ますが、グループ 1 で別の置換を行いたいので、スペースを_.

それは単一のre.sub正規表現で実行できますか?

4

2 に答える 2

3

文字列の代わりに関数を使用できます。

>>> import re
>>> def as_link(match):
...     link = match.group(1)
...     return '<a href="{}">{}</a>'.format(link.replace(' ', '_'), link)
...
>>> text = 'This is a random text. This should be a [[link somewhere]]. And some more text at the end.'
>>> re.sub(r'\[\[(.*?)\]\]', as_link, text)
'This is a random text. This should be a <a href="link_somewhere">link somewhere</a>. And some more text at the end.'
于 2013-10-06T06:18:23.990 に答える
1

このようなことができます。

import re

pattern = re.compile(r'\[\[([^]]+)\]\]')

def convert(text): 
    def replace(match):
        link = match.group(1)
        return '<a href="{}">{}</a>'.format(link.replace(' ', '_'), link)
    return pattern.sub(replace, text)

s = 'This is a random text. This should be a [[link somewhere]]. .....'
convert(s)

実際のデモを見る

于 2013-10-06T06:21:33.970 に答える