千家信息网

认识正则表达式

发表于:2025-02-06 作者:千家信息网编辑
千家信息网最后更新 2025年02月06日,Python里的正则表达式re:pattern:匹配模式,遵循正则表达式语法method:匹配方法,search/match/split/findall/finditer/sub/subnre模块介绍
千家信息网最后更新 2025年02月06日认识正则表达式

Python里的正则表达式re:

pattern:匹配模式,遵循正则表达式语法

method:匹配方法,search/match/split/findall/finditer/sub/subn

re模块介绍

re.search:搜索字符串,找到匹配的第一个字符串

re.match:从字符串开始开始匹配

re.split:使用正则表达式来分隔字符串

re.findall:根据正则表达式从左到右搜索匹配项,返回匹配的字符串列表

re.finditer:根据正则表达式从左到右搜索匹配项,返回一个迭代器返回MatchObject

re.sub:字符串替换

re.subn:与sub一样,返回值多替换的字符串个数

re.group:返回匹配组:索引0表示全部匹配的字符串,索引1开始表示匹配的子组

re.groupdict:返回命名组的字典

re.groups:返回匹配的子组,索引从1开始的所有子组

操作解说示例:

re_demo():    txt=m=.search(,txt)    m.groups()re_method():    s=.search(,s) .match(,s)  .match(,s)re_method_2():    s=.split(,s)re_method_3():    s1=s2=.findall(,s1).findall(,s2)re_method_4():    s2 = i=.finditer(,s2)    m i:        m.group()re_method_5():    s2 = .sub(,,s2)    .subn(, , s2)re_method_6():    data=m=.match(,data)    m.group(,,)    m.groups()__name__==:    re_method_6()


0