zl程序教程

您现在的位置是:首页 >  前端

当前栏目

3.2.3 正则表达式对象

2023-09-14 09:10:34 时间

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

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

从字符串string的开始位置pos开始匹配正则表达式,到位置endpos结束匹配。匹配成功返回match对象,否则返回None。括号中的参数表示可选。比如rx.search(string, 0, 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_Match object; span=(0, 1), match='c'>

None

 

regex.match(string[, pos[, 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_Match object; span=(0, 1), 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', 0,2))

结果输出如下:

regex.fullmatch()

None

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

 

 

regex.split(string, maxsplit=0)

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

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

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

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

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

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

re.sub()一样。

regex.subn(repl, string, 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  深圳