Python:替换标签但保留内部文本?

Rez*_*nor 0 python regex

我有一个字符串.

"This is an [[example]] sentence. It is [[awesome]]".

我想[[.]]<b>.</b>保留匹配的通配符文本替换所有实例.

结果应该是: "This is an <b>example</b> sentence. It is <b>awesome</b>."

我可以进入并手动替换[[with <b>]]with </b>,但是更有意义的是立即执行它并在标记之间保留文本.

我该怎么做呢?

注意:这是从数据库获取源并将其转换为HTML.它应该模仿wiki风格的语法.在这种情况下,[[x]]会产生粗体字样.

aar*_*ing 5

你可以replace在字符串上使用该方法.

>>> s = 'This is an [[example]] sentence. It is [[awesome]].'
>>> s.replace('[[', '<b>').replace(']]', '</b>')

'This is an <b>example</b> sentence. It is <b>awesome</b>.'
Run Code Online (Sandbox Code Playgroud)

只是为了获得一些timeit结果:

$ python -mtimeit -s'import re' "re.sub(r'\[\[(.*?)\]\]', r'<b>\1</b>', 'This is an [[example]] sentence. It is [[awesome]]')"''
100000 loops, best of 3: 19.7 usec per loop

$ python -mtimeit '"This is an [[example]] sentence. It is [[awesome]]".replace("[[", "<b>").replace("]]", "</b>")'
100000 loops, best of 3: 1.94 usec per loop
Run Code Online (Sandbox Code Playgroud)

如果我们编译正则表达式,我们会得到稍微好一点的表现:

$ python -mtimeit -s"import re; r = re.compile(r'\[\[(.*?)\]\]')" "r.sub( r'<b>\1</b>', 'This is an [[example]] sentence. It is [[awesome]]')"
100000 loops, best of 3: 16.9 usec per loop
Run Code Online (Sandbox Code Playgroud)