python之模块3
RE模块使用方法
(1)finditer 返回迭代器
(2)search:只匹配第一个结果
import re res=re.search("\d+","djksf34sa2") print(re.search("\d+","djksf34sa2")) >> <_sre.SRE_Match object; span=(5, 7), match='34'> print(res.group) >> 34
(3)match:只在字符串开始的位置匹配
print(re.match("\d+","22djksf34sa2")) >> <_sre.SRE_Match object; span=(0, 2), match='22'> res=re.match("\d+","22djksf34sa2") print(res.group()) >> 22
(4)split:分割
print(re.split("\d+","fhd123jsk7fhihi5flb5")) >> ['fhd', 'jsk', 'fhihi', 'flb', ''] 限定次数 print(re.split("\d+","fhd123jsk7fhihi5flb5",2)) >> ['fhd', 'jsk', 'fhihi5flb5']
(5)sub:替换 需要三个参数
print(re.sub("\d+","A","hello 24sdf2")) >> hello AsdfA print(re.sub("\d+","A","hello 24sdf2",1))#添加替换次数 >> hello Asdf2 print(re.subn("\d+","A","hello 24sdf2",1))#返回一个元组,并显示替换次数 >> ('hello Asdf2', 1)
(6)compile:编译方法
c=re.compile("\d+") print(c.findall("hello123wof55"))#=======re.findall(“\d+”,”hello123wof55”) >> ['123', '55']