re模块下的常用方法

 1 import re
 2 #1
 3 re.findall('a','alvin yuan')    #返回所有满足匹配条件的结果,放在列表里
 4 #2
 5 re.search('a','alvin yuan').group()  #函数会在字符串内查找模式匹配,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以
 6                                      # 通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
 7  
 8 #3
 9 re.match('a','abc').group()     #同search,不过尽在字符串开始处进行匹配
10  
11 #4
12 ret=re.split('[ab]','abcd')     #先按'a'分割得到''和'bcd',在对''和'bcd'分别按'b'分割
13 print(ret)#['', '', 'cd']
14  
15 #5
16 ret=re.sub('\d','abc','alvin5yuan6',1)
17 print(ret)#alvinabcyuan6
18 ret=re.subn('\d','abc','alvin5yuan6')
19 print(ret)#('alvinabcyuanabc', 2)
20  
21 #6
22 obj=re.compile('\d{3}')
23 ret=obj.search('abc123eeee')
24 print(ret.group())#123

优先级的用法:

1 import re
2 
3 ret=re.findall('www.(baidu|oldboy).com','www.oldboy.com')
4 print(ret)#['oldboy'] 这是因为findall会优先把匹配结果组里内容返回,如果想要匹配结果,取消权限即可
5 
6 ret=re.findall('www.(?:baidu|oldboy).com','www.oldboy.com')
7                     #?:表示去优先级
8 print(ret)#['www.oldboy.com']# import re

 

posted @ 2019-04-14 14:24  挑水工  阅读(168)  评论(0编辑  收藏  举报