1.正则表达式
当我们在Python中使用正则表达式时,re模块内部会干两件事情:
1. 编译正则表达式,如果正则表达式的字符串本身不合法,会报错。
2. 用编译后的正则表达式去匹配字符串。#导入正则表达式模块 >> import re #正则匹配电话 >> re.match(r'\d{3}\-\d{3,8}$','010-123456') <_sre.SRE_Match object at 0x7f6632534648> #普通的字符串分割 >> 'a b c'.split(' ') ['a', 'b', '', 'c'] #使用正则分割字符串 >> re.split(r'\s+','a b c') ['a', 'b', 'c'] #分组(提取字符串的子串) >> m = re.match(r'^(\d{3})-(\d{3,8})$','010-12345') >> m <_sre.SRE_Match object at 0x7f66325eda48> #获取原字符串 >> m.group(0) '010-12345' #获取分组字符串 >> m.group(1) '010' >> m.group(2) '12345' #非贪婪匹配(正则默认是贪婪匹配) #要让\d+采用非贪婪匹配,只用在后面加上一个?就可以了 >> re.match(r'^(\d+?)(0*)$','102300').groups() ('1023', '00') #正则表达式的预编译 >> re_telephone = re.compile(r'^(\d{3})-(\d{3,8})$') #使用编译好的正则表达式 >> re_telephone.match('010-12345').groups() ('010', '12345')
249

被折叠的 条评论
为什么被折叠?



