1.3.10 用模式修改字符串
除了搜索文本之外,re还支持使用正则表达式作为搜索机制来修改文本,而且替换(replacement)可以引用模式中的匹配组作为替代文本的一部分。使用sub()可以将 一个模式的所有出现替换为另一个字符串。
import re
bold = re.compile(r'\*{2}(.*?)\*{2}')
text = 'Make this **bold**. This **too**.'
print('Text:',text)
print('Bold:',bold.sub(r'<b>\1</b>',text))
可以使用向后引用的\num语法插入与模式匹配的文本的引用。
运行结果:
要在替换中使用命名组,可以使用语法\g。
import re
bold = re.compile(r'\*{2}(?P<bold_text>.*?)\*{2}')
text = 'Make this **bold**. This **too**.'
print('Text:',text)
print('Bold:',bold.sub(r'<b>\g<bold_text></b>',text))
\g语法还适用于编号引用,只用这个语法可以消除组编号和外围字面量数字之间的模糊性。
运行结果:
向count传入一个值可以限制完成的替换数。
import re
bold = re.compile(r'\*{2}(.*?)\*{2}')
text = 'Make this **bold**. This **too**.'
print('Text:',text)
print('Blod:',bold.sub(r'<b>\1</b>',text,count=1))
由于count为1,所以只完成了第一个替换。
运行结果:
subn()的工作与sub()很相似,只是它会同时返回修改后的字符串和完成的替换数。
import re
bold = re.compile(r'\*{2}(?P<bold_text>.*?)\*{2}')
text = 'Make this **bold**. This **too**.'
print('Text:',text)
print('Bold:',bold.subn(r'<b>\g<bold_text></b>',text))
这个例子中搜索模式有两次匹配。
运行结果: