python 正则表达式 re.sub & re.subn

Grammar:

re.sub(pattern, repl, string[, count])

使用repl替换string中每一个匹配的子串后返回替换后的字符串。
当repl是一个字符串时,可以使用\id或\g、\g引用分组,但不能使用编号0。
当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。
count用于指定最多替换次数,不指定时全部替换。

re.subn(pattern, repl, string[, count])

返回 (sub(repl, string[, count]), 替换次数)。

Case:

 1 #coding=utf-8
 2 
 3 import re
 4 
 5 str = "https://i.cnb1logs.co2m/Edi3tPosts.asp4x?opt=999"
 6 
 7 
 8 pattern=re.compile(r'(\.)')
 9 print '\.          :' ,re.sub(pattern,'-',str)
10 
11 pattern=re.compile(r'\/([^*]+)\/')
12 print '\/([^*]+)\/ :' ,re.sub(pattern,r'<em>\1<em>',str)
13 
14 pattern = re.compile(r'(\w+)(\w+)(\d+)')
15 #先切片测试
16 print re.split(pattern,str)
17 print re.sub(pattern,r'\3 \1',str)
18 #subn统计sub替换次数
19 print re.subn(pattern,r'\3 \1',str)  

Output

1 \.          : https://i-cnb1logs-co2m/Edi3tPosts-asp4x?opt=999
2 \/([^*]+)\/ : https:<em>/i.cnb1logs.co2m<em>Edi3tPosts.asp4x?opt=999
3 ['https://i.', 'cn', 'b', '1', 'logs.', 'c', 'o', '2', 'm/', 'Ed', 'i', '3', 'tPosts.', 'as', 'p', '4', 'x?opt=', '9', '9', '9', '']
4 https://i.1 cnlogs.2 cm/3 EdtPosts.4 asx?opt=9 9
5 ('https://i.1 cnlogs.2 cm/3 EdtPosts.4 asx?opt=9 9', 5)
6 
7 ***Repl Closed***

 

 

 

 

 

 

 

 

 

 

 

 

 

 

quote:http://cuiqingcai.com/977.html

posted on 2017-12-01 14:24  sub2020  阅读(3552)  评论(0编辑  收藏  举报

导航