标签:测试 扫描 import sea object 正则表达 family obj imp
一、re模块的match函数
re.match 从字符串的起始匹配,如果不是在起始位置匹配成功,match()返回None
匹配成功返回一个匹配的对象,不成功返回None
测试数据:
p = re.compile("[0-9]")
m = p.match(‘14534Abc‘)
m2 = p.match(‘sdsdf453‘)
print(m)
print(m.group())
print(m.span())
print(m.groups())
print("============")
print(m2)
测试结果:
<_sre.SRE_Match object; span=(0, 1), match=‘1‘>
1
(0, 1)
()
============
None
二、re.search 扫描整个字符串返回第一个成功的匹配
匹配成功返回一个匹配的对象,不成功返回None
测试数据:
import re
p = re.compile("[0-9]")
m = p.search(‘14534Abc‘)
m2 = p.search(‘sdsdf453‘)
print(m)
print(m.group())
print(m.span())
print(m.groups())
print("============")
print(m2)
print(m2.group())
print(m2.span())
print(m2.groups())
测试结果:
<_sre.SRE_Match object; span=(0, 1), match=‘1‘>
1
(0, 1)
()
============
<_sre.SRE_Match object; span=(5, 6), match=‘4‘>
4
(5, 6)
()
三、re模块的group和groups
group 和 groups 是两个不同的函数
m.group()== m.group(0) == 返回所有匹配到的字符
m.group(N) 返回第N组括号匹配到的字符
m.groups() 返回所有括号匹配到的字符,以元组格式存储
m.groups() = (m.group(1),m.group(2),....)
测试数据:
line = "Cats are smarter than dogs"
matchObj = re.match(r‘(.*) are (.*?) .*‘, line, re.M | re.I)
if matchObj:
print("matchObj.group: ", matchObj.group)
print("matchObj.group() : ", matchObj.group())
print("matchObj.group() : ", matchObj.group(0))
print("matchObj.group(1) : ", matchObj.group(1))
print("matchObj.group(2) : ", matchObj.group(2))
else:
print("No match!!")
print(matchObj.groups())
print(matchObj.groups()[0])
print(matchObj.groups()[1])
测试结果:
matchObj.group: <built-in method group of _sre.SRE_Match object at 0x10f5ffe00>
matchObj.group() : Cats are smarter than dogs
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
(‘Cats‘, ‘smarter‘)
Cats
smarter
标签:测试 扫描 import sea object 正则表达 family obj imp
原文地址:https://www.cnblogs.com/python-test/p/9335866.html