2014-02-05 56 views
-3

我有一些文字,例如:的Python:替换一些标签的HTML字符串变量

我的文字\ B的最优\ b

,但我不能做到这一点\任务,因为

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

我如何与HTML标记替换这些标签,如下列:

我的文字最好

但由于

这是福,我不能做这个任务**正则表达式?和其他文字

标记\ b成对,但\不成对,并且只能包含下一个单词。

回答

1

使用两个单独的更换:

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