本文共 1036 字,大约阅读时间需要 3 分钟。
import reprint(re.search("xyx","qxyasdfxuyxyxaqd"))#寻找print(re.match("xya","qxyasdfxuyxyxaqd"))#从头匹配,失败返回Noneprint(re.match("qxy","qxyasdfxuyxyxaqd"))#从头匹配,失败返回Noneprint(re.sub('xy',"XY","xyaaxy"))#替换pattern=re.compile(r'(\d+)(\D*)(\d+)')#匹配至少一个数字,编译正则表达式生成一个对象,以后用这个对象作为其它函数参数调用print(pattern.match("asdfaf1231sss"))#从头匹配m2=pattern.search("asd24faf456.31dd1231aaa")#寻找第一个匹配print(m2)#所有匹配部分print(m2.group(0))#第一部分print(m2.group(1))#第二部分print(m2.group(2))print(m2.group(3))res=pattern.findall("asd24faf456b31dd1231aaa")#找到所有匹配子串。返回列表print(res)it=re.finditer(r"\d+","aw123ad5a2114yyi809vv")#找到所有匹配子串,返回迭代器for match in it: print(match.group())print(re.split("\d+","aw123ad5a2114yyi809vv"))#按匹配的子串将字符串分割后返回列表
<_sre.SRE_Match object; span=(10, 13), match='xyx'>
None<_sre.SRE_Match object; span=(0, 3), match='qxy'>XYaaXYNone<_sre.SRE_Match object; span=(3, 11), match='24faf456'>24faf45624faf456[('24', 'faf', '456'), ('31', 'dd', '1231')]12352114809['aw', 'ad', 'a', 'yyi', 'vv']转载于:https://blog.51cto.com/13959448/2325598