python正则表达式复习4

使用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.’

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值