匹配搜索 match,search,findall区别

匹配搜索 match,search,findall区别

match首字母搜索匹配,匹配即停止

import re
re.match(r'de','de8ug').group() 
'de'
re.match(r'de','8ugde').group()  
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-37-4da79a63dcbc> in <module>()
----> 1 re.match(r'de','8ugde').group()  # 只能首字母匹配

AttributeError: 'NoneType' object has no attribute 'group'

search所有字母搜索匹配,匹配即停止

re.search(r'de','8ugde').group() 
'de'
re.search(r'de','de8ug').group() 
'de'
re.search('de','8ugde 88deug').group() 
'de'

match和search结合group使用

re.match(r"(\w+) (\w+)", "Isaac Newton, physicist").group() # 首字母匹配,匹配即停止
'Isaac Newton'
re.match(r"(\w+) (\w+)", "Isaac Newton, physicist").group(1)
'Isaac'
re.match(r"(\w+) (\w+)", "Isaac Newton, physicist").group(2)
'Newton'
re.search(r"(\w+) (\w+)", "IsaacNewton, physicist fsdf").group()
'physicist fsdf'
re.search(r"(\w+) (\w+)", "Isaac Newton, physicist fsdf").group()  # 所有字母匹配,匹配即停止
'Isaac Newton'
re.search(r"(\w+) (\w+)", "Isaac Newton, physicist fsdf").group(1)
'Isaac'
re.search(r"(\w+) (\w+)", "Isaac Newton, physicist fsdf").group(2)
'Newton'

findall 找到所有匹配的内容

re.findall(r"(\w+) (\w+)", "Isaac Newton, physicist fsdf") # 找到所有匹配的内容,返回一个列表
[('Isaac', 'Newton'), ('physicist', 'fsdf')]
re.findall(r"(\w+) (\w+)", "Isaac Newton, physicist fsdf")[0]
('Isaac', 'Newton')
re.findall(r"(\w+) (\w+)", "Isaac Newton, physicist fsdf")[1]
('physicist', 'fsdf')

返回类型

type(re.match(r"(\w+) (\w+)", "Isaac Newton, physicist").group()) # 返回字符串
str
type(re.search(r"(\w+) (\w+)", "Isaac Newton, physicist").group()) # 返回字符串
str
type(re.findall(r"(\w+) (\w+)", "Isaac Newton, physicist fsdf"))  # 返回列表
list

猜你喜欢

转载自blog.51cto.com/13587169/2128240