Python:将一些标记替换为字符串中的html标记

Python:将一些标记替换为字符串中的html标记,python,html,regex,Python,Html,Regex,我有一些文字,例如: 我的文字\b最好\b 但是我不能做这个任务,因为 这是fu**regex?和其他文本 如何用HTML标记替换这些标记,如下所示: 我的文字是最好的 但是我不能做这个任务,因为 这是fu**regex?和其他文本 标记\b成对,但\a不成对,必须只包含下一个单词。使用两个单独的替换: sample = re.sub(r'\\b(.*?)\\b', r'<h5>\1</h5>', sample) sample = re.sub(r'\\a(\s*\w+)

我有一些文字,例如:

我的文字\b最好\b

但是我不能做这个任务,因为

这是fu**regex?和其他文本

如何用HTML标记替换这些标记,如下所示:

我的文字是最好的

但是我不能做这个任务,因为

这是fu**regex?和其他文本


标记\b成对,但\a不成对,必须只包含下一个单词。

使用两个单独的替换:

sample = re.sub(r'\\b(.*?)\\b', r'<h5>\1</h5>', sample)
sample = re.sub(r'\\a(\s*\w+)', r'<a href="#task">\1</a>', sample)
演示:

>>> import re
>>> sample = '''\
... My text \\b the best \\b
... but i cant do this \\a task because
... this is fu** regex? And other text
... '''
>>> sample = re.sub(r'\\b(.*?)\\b', r'<h5>\1</h5>', sample)
>>> sample = re.sub(r'\\a(\s*\w+)', r'<a href="#task">\1</a>', sample)
>>> sample
'My text <h5> the best </h5>\nbut i cant do this <a href="#task"> task</a> because\nthis is fu** regex? And other text\n'
>>> print sample
My text <h5> the best </h5>
but i cant do this <a href="#task"> task</a> because
this is fu** regex? And other text