其他分享
首页 > 其他分享> > 正则表达式 findall()与match()的区别

正则表达式 findall()与match()的区别

作者:互联网

findall()返回所有匹配结果的列表

match()返回所有分组的object

 

#!/usr/bin/python
import re
line = "Cats are smarter than dogs "

#findall用来返回所有匹配的的list
pattern = re.compile( r'(.*) are (.+? )+')
matchObj = pattern.findall(line)
if matchObj:
    print("matchObj : ", matchObj)
else:
    print("No match!!")

'''
output:
matchObj :  [('Cats', 'dogs ')]
'''
findall()

 

#!/usr/bin/python
import re
line = "Cats are smarter than dogs "

#match用来查找分组,返回是个分组的object
pattern = re.compile( r'(.*) are (.+? )+')
matchObj = pattern.match(line)
if matchObj:
    #group()匹配正则表达式整体结果
    print("matchObj.group(0) : ", matchObj.group())
    print("matchObj.group(1) : ", matchObj.group(1))
    print("matchObj.group(2) : ", matchObj.group(2))
else:
    print("No match!!")

'''
output:
matchObj.group(0) :  Cats are smarter than dogs 
matchObj.group(1) :  Cats
matchObj.group(2) :  dogs 

'''
match()

 

标签:group,正则表达式,matchObj,Cats,print,findall,match
来源: https://www.cnblogs.com/songshutai/p/15860217.html