標籤:print coding pytho color enc 工作 odi 規則 python
本文執行個體講述了Python正則替換字串函數re.sub用法。分享給大家供大家參考,具體如下:
python re.sub屬於python正則的標準庫,主要是的功能是用正則匹配要替換的字串
然後把它替換成自己想要的字串的方法
re.sub 函數進行以Regex為基礎的替換工作
下面是一段樣本源碼
1 #!/usr/bin/env python2 #encoding: utf-83 import re4 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 [[email protected] 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,表示每個匹配項都替換
Python正則替換字串函數re.sub用法樣本(1)