正则表达式

 1 import re
 2 
 3 #在一个字符串中搜索匹配正则表达式的第一个位置,返回match对象
 4 match = re.search(r'[1-9]\d{5}', 'BIT 100081')
 5 if match:
 6     print(match.group(0))
 7 
 8 #从一个字符串的开始位置起匹配正则表达式,返回match对象
 9 match = re.match(r'[1-9]\d{5}', 'BIT 100081')
10 if match: #是空的
11     print(match.group(0))
12 
13 match = re.match(r'[1-9]\d{5}', '100081 BIT ')
14 if match: #从开头开始搜索
15     print(match.group(0))
16 
17 #以列表类型返回全部能匹配的字串
18 ls = re.findall(r'[1-9]\d{5}', 'BIT100081 TSU100084')
19 print(ls) #输出为列表
20 
21 #分隔字符串
22 a1=re.split(r'[1-9]\d{5}', 'BIT100081 TSU100084')
23 print(a1) #用邮编作为分隔符
24 a2=re.split(r'[1-9]\d{5}', 'BIT100081 TSU100084', maxsplit=1)
25 print(a2) #最多分隔一次
26 
27 #返回匹配结果的迭代类型,每一个迭代元素是match对象,可以单独进行处理
28 for m in re.finditer(r'[1-9]\d{5}', 'BIT100081 TSU100084'):
29     if m:
30         print(m.group(0))
31 
32 #替换
33 a3=re.sub(r'[1-9]\d{5}', ':zipcode', 'BIT100081 TSU100084')
34 print(a3)
35 
36 #一次调用
37 match = re.search(r'[1-9]\d{5}', 'BIT 100081')
38 #等价于
39 #对象的形式
40 regex = re.compile(r'[1-9]\d{5}')
41 match = regex.search(regex, 'BIT 100081')

#Match对象的属性
#.string 待匹配文本
#.re 匹配时使用的pattern对象(正则表达式)
#.pos 正则表达式搜索文本的开始位置
#.endpos正则表达式搜索文本的结束位置

#.group(0) 返回匹配后的字符串
#.start() .end() .span()

#re默认采用贪婪匹配,输出最长匹配的字符串
#如果想返回最小匹配,需要 添加最小匹配操作符

posted @ 2017-06-17 01:13  大蓝鲸  阅读(210)  评论(0编辑  收藏  举报