加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

3.2.3 正则表达式对象

发布时间:2020-12-14 01:01:07 所属栏目:百科 来源:网络整理
导读:编译之后的正则表达式对象支持的方法和属性如下: regex.search(string[,pos[,endpos]]) 从字符串 string 的开始位置 pos 开始匹配正则表达式,到位置 endpos 结束匹配。匹配成功返回 match 对象,否则返回 None 。括号中的参数表示可

编译之后的正则表达式对象支持的方法和属性如下:

regex.search(string[,pos[,endpos]])

从字符串string的开始位置pos开始匹配正则表达式,到位置endpos结束匹配。匹配成功返回match对象,否则返回None。括号中的参数表示可选。比如rx.search(string,50)等价于rx.search(string[:50],0)

例子:

print('regex.search()')

pattern=re.compile('c')

print(pattern.search('caimouse'))

print(pattern.search('caimouse',1))

结果输出如下:

regex.search()

<_sre.SRE_Matchobject;span=(0,1),match='c'>

None

regex.match(string[,endpos]])

指定从字符串string头部或者指定位置的头部匹配。参数pos默认值为0,表示从字符串指定位置开始进行匹配。参数endpos匹配结束位置。如果搜索字符串任意位置所有字符串,需要使用regex.search()方法。

例子:

print('regex.match()')

pattern=re.compile('c')

print(pattern.match('caimouse'))

print(pattern.match('caimouse',1))

结果输出如下:

regex.match()

<_sre.SRE_Matchobject;span=(0,match='c'>

None

regex.fullmatch(string[,pos,endpos]])

当整个string与正则表达式匹配时返回match对象,否则返回None。参数posendpossearch()的意义一样。

例子:

print('regex.fullmatch()')

pattern=re.compile('c[ai]')

print(pattern.fullmatch('caimouse'))

print(pattern.fullmatch('caimouse',2))

结果输出如下:

regex.fullmatch()

None

<_sre.SRE_Matchobject;span=(0,2),match='ca'>

regex.split(string,maxsplit=0)

本方法与re.split()一样。

regex.findall(string[,endpos]])

re.findall()一样,本方法接收参数posendpos参数,可以指定开始位置和结束位置。

regex.finditer(string[,endpos]])

re.finditer()一样,本方法接收参数posendpos参数,可以指定开始位置和结束位置。

regex.sub(repl,string,count=0)

re.sub()一样。

regex.subn(repl,count=0)

re.subn()一样。

regex.flags

regex匹配的标志。

例子:

print('regex.flags')

pattern=re.compile('c[ai]')

print(pattern.fullmatch('caimouse'))

print(pattern.flags)

pattern=re.compile('c[ai]',re.ASCII)

print(pattern.flags)

结果输出如下:

regex.flags

None

32

256

regex.groups

正则表达式匹配分组的数量。

例子:

print('regex.groups')

pattern=re.compile('(?P<style>[^|]*)|(?P<tags>[^|]*)')

print(pattern.findall('OL|AAAAA'))

print(pattern.groups)

结果输出如下:

regex.groups

[('OL','AAAAA')]

2

regex.groupindex

返回分组的名称和序号,以字典方式返回。如果没有返回空字典。

例子:

print('regex.groups')

pattern=re.compile('(?P<style>[^|]*)|(?P<tags>[^|]*)')

print(pattern.findall('OL|AAAAA'))

print(pattern.groups)

print(pattern.groupindex)

结果输出如下:

regex.groups

[('OL','AAAAA')]

2

{'style':1,'tags':2}

regex.pattern

已经编译的正则表达式的字符串。

例子:

print('regex.pattern')

pattern=re.compile('(?P<style>[^|]*)|(?P<tags>[^|]*)')

print(pattern.findall('OL|AAAAA'))

print(pattern.pattern)

结果输出如下:

regex.pattern

[('OL','AAAAA')]

(?P<style>[^|]*)|(?P<tags>[^|]*)


蔡军生 QQ:9073204 深圳

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读