import re
x= re.search('oob', 'www.runoob.com') #返回的是个一个元组,匹配下标索引
#如果re.search没有匹配上,则span函数会报错,需要先使用if条件判断一下是否是None对象
if x is not None:
y=x.group(0)
else:
y="NA"
y
#y="www"[x.span()[0]:x.span()[1]]
'oob'
#python中正则表达式使用group来分组
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
if matchObj:
y1=matchObj.group()
y2=matchObj.group(1)
y3=matchObj.group(2)
else:
y1="No match!!"
[y1,y2,y3]
['Cats are smarter than dogs', 'Cats', 'smarter']
if (re.match(r'w{3}', 'www.runoob.com')):
x="yes"
else:
x="no"
x
#re.match 和 re.search第一个参数为正则表达式,第二个为需要匹配的文本,返回值的类型为逻辑类型
#match只能匹配从头开始
'yes'
if (re.search(r'abc', 'www.runoob.com')):
x="yes"
else:
x="no"
x
'no'
使用findall函数
text = "foo bar\t baz \tquxfo"
re.split('\s+', text)
re.findall(pattern=r"fo{1,2}",string=text)
#findall返回的是一个列表数组,找出所有的匹配项