当前位置: 首页 > 后端技术 > Python

Python3常用正则表达式

时间:2023-03-26 19:36:13 Python

常用函数:1.re.match开始位置匹配,没有匹配则返回(即使正则表达式开头不使用^声明匹配)input="entrystation"#Pgroupnamereg=re.compile(r'(?PGettingstarted)')res=reg.match(input)ifres:print(res.groupdict())print(res.groups())print(res.groups()){'name':'GettingStarted'}('GettingStarted',)('GettingStarted',)2.re.searchSearchthewholestring#扫描整个字符串找到匹配模式的第一个位置,并返回一个对应的匹配对象。如果没有匹配,返回一个Noneinput='''GettingStartedwithaSmallStationGettingStartedwithaTutorial'''reg=re.compile(r'GettingStarted(?:Station|Tutorial)',re.S)res=reg.search(input)ifres:print(res.group())入门小站3.re.findall查找字符串的所有匹配项,返回一个listinput='''入门小站gettingStartedTutorial'''#re.M多行模式匹配reg=re.compile(r'^GettingStarted(?:Station|Tutorial)$',re.M)res=reg.findall(input)ifres:print(res)['入门小站','入门教程']4.re.split字符串分割#split(pattern,string,maxsplit=0,flags=0)#maxsplit最大分割数input='''入门123小站dd入门'''reg=re.compile(r'[a-z0-9]+')res=reg.split(input)print(res)reg=re.compile(r'[a-z0-9]+')res=reg.split(input,1)print(res)['\n入门\n','\nStation\n','\n入门\n']['\nGettingstarted\n','\nStation\ndd\nGettingStarted\n']5。re.substringreplacement#语法sub(pattern,repl,string,count=0,flags=0)#repl被字符串替换#count指定替换次数数字input='''123小站入门456dd'''reg=re.compile(r'([a-z0-9]{1,})',re.M)res=reg.sub('11',input)print(res)#替换一次reg=re.compile(r'([a-z0-9]{1,})',re.M)res=reg.sub('11',input,1)print(res)GettingStarted11Station1111GettingStartedGettingStarted11Station456ddGettingStarted6.re.subn#语法subn(pattern,repl,string,count=0,flags=0)#characterreplacedbyreplString#count指定替换次数#返回结果包含替换次数input='''入门123小站456dd入门'''reg=re.compile(r'([a-z0-9]{1,})',re.M)res=reg.subn('11',input)print(res)('\n入门\n11\n小站\n11\n11\n入门\n',3)