re 模块
import re #findall 匹配所有匹配项,返回一个列表 # ret=re.findall('\d+','hello123,word456') # print(ret) #findall 分组优先原则 显示()的内容 ret=re.findall('\d(\d+)','a12,b34,c567') print(ret) #输出 ['2', '4', '67'] #先分配,分配给\d的不显示,显示()分组的 # 1,3,5分配给\d了 #取消分组优先的规则 ?: # ret=re.findall('\d(?:\d+)','a12,b34,c56') # print(ret)
#search 只匹配第一个匹配项,返回一个对象,需要用.group()取值 # ret=re.search('\d+','hello123,word456') # print(ret.group()) #match 等于search 加了^号 必须以..开头才能匹配 # ret=re.match('\d[A-z]','22hello123,word456') # print(ret.group()) #输出 22hello
# re.split() 根据规则切割,如果最后部分切掉了,会返回一个空的字符串 # s='wind666is777are88' # ret=re.split('\d+',s) # print(ret) # ['wind', 'is', 'are', ''] # s='wind666is777are88sdf' # ret=re.split('\d+',s) # print(ret) # ['wind', 'is', 'are', 'sdf']
#sub 替换 sub(规则,替换成,替换的字符串) # ret=re.sub('\d+','糖果','hello123,word456') # print(ret) # # ret=re.sub('\d+','糖果','hello123,word456',1) #指定替换的个数 # print(ret) # re.compile() 预编译,降低时间成本 # ret=re.compile('\d+') #先编译规则 # ret1=ret.findall('hello123,word456') # print(ret1) # re.finditer() #节省空间,变成迭代器 # ret=re.finditer('\d+','hello123,word456') # for i in ret: # print(i.group())