Python正则替换字符串函数re.sub

python re.sub属于python正则的标准库,主要是的功能是用正则匹配要替换的字符串
然后把它替换成自己想要的字符串的方法
re.sub 函数进行以正则表达式为基础的替换工作

1 #!/usr/bin/env python
2 #encoding: utf-8
3 import re
4 url = 'https://113.215.20.136:9011/113.215.6.77/c3pr90ntcya0/youku/6981496DC9913B8321BFE4A4E73/0300010E0C51F10D86F80703BAF2B1ADC67C80-E0F6-4FF8-B570-7DC5603F9F40.flv'
5 pattern = re.compile(r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])')
6 print pattern.findall(url)
7 out = re.sub(pattern, '127.0.0.1', url)
8 print out

执行结果:

1 [root@CentOS-7 shu]# python re_sub.py 
2 ['113.215.20.136', '113.215.6.77']
3 https://127.0.0.1:9011/127.0.0.1/c3pr90ntcya0/youku/6981496DC9913B8321BFE4A4E73/0300010E0C51F10D86F80703BAF2B1ADC67C80-E0F6-4FF8-B570-7DC5603F9F40.flv

re.sub 函数详解:

           命令:re.sub(pattern, repl, string, count=0, flags=0)

             re.sub 用于替换字符串的匹配项。如果没有匹配到规则,则原字符串不变。

            第一个参数:规则 
            第二个参数:替换后的字符串 
            第三个参数:字符串 
            第四个参数:替换个数。默认为0,表示每个匹配项都替换

还可以这样:

tempstr = "hello you hello python are you ok"
import re
rex = r'(hello|Use)'
print re.sub(rex,"Bye",tempstr)

python中最简单的替换字符串 ,利用本身的函数:

#最简单的方法使用replace()
tempstr = "hello you hello python are you ok"
print tempstr.replace("you","python")

  

 

posted @ 2018-09-06 09:10  zxf123  阅读(1582)  评论(1编辑  收藏  举报