# coding=gbk import re class regularExp: # ^ 是匹配以什么字符串开始 $是匹配以什么字符串结束 def matchEmail(self, matchStr): matchResult = re.match(r'^[\w]{4,6}@qq.com$', matchStr) print("matchResult email:{0}".format(matchResult)) def matchEmail2(self, matchStr): matchResult = re.match(r'^[\w]?@qq.com$', matchStr) print("matchResult email:{0}".format(matchResult)) def matchNumber(self, matchNumber): matchResult = re.match(r'[1-9]?\d$', matchNumber) print("matchResult number:{matchResult}".format(matchResult=matchResult)) def matchEmailImprove(self, matchEmailStr): matchResult = re.match(r'[\w]{4,6}@(qq|126).com$', matchEmailStr) print("matchResult matchEmailStr:{matchResult}".format(matchResult=matchResult)) def matchEmailImprove2(self, matchEmailStr): matchResult = re.match(r'[\w]{4,6}@[qq|126].com$', matchEmailStr) print("matchResult matchEmailStr2:{matchResult}".format(matchResult=matchResult)) def matchXmlElement(self, xmlStr): matchResult = re.match(r'<[\w]+>', xmlStr) print("matchResult xmlStr:{matchResult}".format(matchResult=matchResult.group())) # \1是对()的第一个分组 ()是分组的意思 \1 引用第一个分组 def matchGroupXmlElement(self, xmlStr): matchResult = re.match(r'<([\w]+>)[\w]+</\1', xmlStr) print("matchResult matchGroupXmlElement:{matchResult}".format(matchResult=matchResult.group())) # (?P<名称>) 自定义分组名称 (?P=名称)引用自定义分组名称 def matchGroupNameXmlElement(self, xmlStr): matchResult = re.match(r'<(?P<mark>[\w]+>)[\w]+</(?P=mark)', xmlStr) print("matchResult matchGroupNameXmlElement:{matchResult}".format(matchResult=matchResult.group())) # search 找到一个就返回 def searchStr(self, sourceStr): serchResult = re.search(r'\d+', sourceStr) print("matchResult serchStr:{matchResult}".format(matchResult=serchResult.group())) def findAllStr(self, sourceStr): serchResult = re.findall(r'\d+', sourceStr) print("matchResult findAllStr:{matchResult}".format(matchResult=serchResult)) def subStr(self, sourceStr): subResult = re.sub(r'\d+', '999', sourceStr) print("matchResult subhResult:{subResult}".format(subResult=subResult)) # 对匹配的结果做变更 def subUpdateStr(self, sourceStr): subResult = re.sub(r'\d+', self.addOne, sourceStr) print("matchResult subUpdateStr:{subResult}".format(subResult=subResult)) def addOne(self,match): val = match.group() num = int(val) + 90 return str(num) def splitStr(self,sourceStr): splitResult = re.split(r':| |,', sourceStr) print("matchResult splitResult:{splitResult}".format(splitResult=splitResult)) if __name__ == '__main__': rg = regularExp() rg.matchEmail("9999@qq.com1") rg.matchEmail2("1h@qq.com") rg.matchNumber('91') rg.matchEmailImprove('hrao@126.com') rg.matchXmlElement('<book>python</book>') rg.matchGroupXmlElement('<book>python</book>') rg.matchGroupNameXmlElement('<book>python</book>') rg.searchStr('immoc videaNum=1000 好 2345') rg.findAllStr('immoc videaNum=1000 好 2345') rg.subStr('immoc videaNum=1000 好 2345') rg.subUpdateStr('immoc videaNum=1000 好 2000') rg.splitStr('hello world:my name is xiao ming,are you ok')
python中的真则表达式
最新推荐文章于 2023-11-07 10:25:12 发布