码迷,mamicode.com
首页 > 其他好文 > 详细

匹配搜索 match,search,findall区别

时间:2018-06-11 22:46:08      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:python

匹配搜索 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

匹配搜索 match,search,findall区别

标签:python

原文地址:http://blog.51cto.com/13587169/2128240

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!