python之正则表达式使用
# -*- coding: utf-8 -*- """ Created on Tue Dec 17 19:29:44 2019 @author: xbxia """ import random import re #按规则生成指定数量的sn号 def save(count): with open('devSn.txt', 'a+') as fw_t: for i in range(0, count): devSn = ('hongdian'+"%08d"%(i)) print(devSn) fw_t.write(devSn) fw_t.write('\n') #正则表达式用法 #从起始位置匹配数字 def match_pattern(content,start,end): pattern = re.compile(r'\d+') result_obj = pattern.match(content,start,end) result = result_obj.group() #取出匹配的内容 #print(result) return result #找出字符串个数 def findall_pattern(content): pattern = re.compile('hongdian') result = pattern.findall(content) #print(result) return len(result) #指定位置搜索整个字符串,但只返回第一个匹配结果 def search_pattern(content,pos): pattern = re.compile('hongdian') result = pattern.search(content,pos) print(result) if __name__ == '__main__': #save(100) #match_pattern(content,20,22) content = 'h88dhonghhhhhongdian000hongdian' search_pattern(content,22)
本文来自博客园,作者:ReluStarry,转载请注明原文链接:https://www.cnblogs.com/relustarry/p/12588529.html