正则表达式 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()

 

posted @ 2022-02-02 12:23  yudai  阅读(91)  评论(0编辑  收藏  举报