Python替换标签之间的字符串

Gra*_*GTO 0 python

我想做一个简单的自制bbcode。

字符串示例:

s = 'Hello world, this is my website {url}myURL{/url}'
Run Code Online (Sandbox Code Playgroud)

我要替换{url}myURL{/url}<a href="myURL">myURL</a>

如果有人有解决方案,那会很好吗?

Rak*_*esh 5

使用 re.sub

例如:

import re

s = 'Hello world, this is my website {url}myURL{/url}'
print(re.sub(r"{url}(.*?){\/url}", r'<a href="\1">\1</a>', s))
Run Code Online (Sandbox Code Playgroud)

输出:

Hello world, this is my website <a href="myURL">myURL</a>
Run Code Online (Sandbox Code Playgroud)