正则表达式搜索并替换为修改后的结果

时间:2015-08-14 20:18:06

标签: python regex

我有一个带有标记元素的字符串。我想删除标签并在标签内的内容中添加一些字符。

s = 'Hello there <something>, this is more text <tagged content>'
result = 'Hello there somethingADDED, this is more text tagged contentADDED

到目前为止,我已经尝试了

import re
result = re.search('\<(.*)\>', s)
result = result.group(1)

s = s.split('>')和正则表达式每个子字符串一个接一个,但它似乎不是正确或有效的方法。

1 个答案:

答案 0 :(得分:3)

使用back-reference \1

x="Hello there <something>, this is more text <tagged content>"
print re.sub(r"<([^>]*)>",r"\1added",x)

输出:Hello there somethingadded, this is more text tagged contentadded

相关问题