使用sub方法替换字符串
import re
# 将双星号替换成功<b>
bold = re.compile(r'\*{2}(.*?)\*{2}')
text = 'Make this **bold**. This **too**.'
print 'Text:', text
# 这里'\1',代表(.*?),也就是找到的字符串
print 'Bold:', bold.sub(r'<b>\1</b>', text)
结果
Text: Make this **bold**. This **too**.
Bold: Make this < b>bold< /b>. This < b>too< /b>.
替换的时候使用组名
# bold_text组
bold = re.compile(r'\*{2}(?P<bold_text>.*?)\*{2}', re.UNICODE)
text = 'Make this **bold**. This **too**.'
print 'Text:', text
print 'Bold:', bold.sub(r'<b>\g<bold_text></b>', text)
结果
Text: Make this **bold**. This **too**.
Bold: Make this < b>bold< /b>. This < b>too< /b>.
指定替换哪一个
#指定group的数count,因此第一个**bold**会被替换掉
print 'Bold:', bold.sub(r'<b>\1</b>', text, count=1)
结果
Bold: Make this < b>bold< /b>. This **too**.
subn会返回替换的字符串和数目
#subn与sub的使用类似,不过subn会返回改变的字符串以及替换的数目
print 'Bold:', bold.subn(r'<b>\1</b>', text)
结果
Bold: (‘Make this < b>bold< /b>. This < b>too< /b>.’, 2)
使用split进行分割
text = '''Paragraph one
on two lines.
Paragraph two.
Paragraph three.'''
# 第一段落和第二段落含有两个以上换行符
for num, para in enumerate(re.findall(r'(.+?)\n{2,}',
text,
flags=re.DOTALL)
):
print num, repr(para)
#通过re.split,以两个换行符进行分割
print 'With split:'
for num, para in enumerate(re.split(r'\n{2,}', text)):
print num, repr(para)
结果
0 ‘Paragraph one\non two lines.’
1 ‘Paragraph two.’
With split:
0 ‘Paragraph one\non two lines.’
1 ‘Paragraph two.’
2 ‘Paragraph three.’