Python正则表达式:替换组内

时间:2013-10-06 06:12:21

标签: python regex string-substitution

有没有办法在小组上进行替换?

假设我正在尝试根据自定义格式插入文本链接。所以,给出这样的东西:

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正则表达式是否可行?

2 个答案:

答案 0 :(得分: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.'

答案 1 :(得分: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)

请参阅working demo

相关问题