匹配搜索 match,search,findall区别
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了匹配搜索 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
以上是关于匹配搜索 match,search,findall区别的主要内容,如果未能解决你的问题,请参考以下文章
Python全栈--6.1-match-search-findall-group(s)的区别以及计算器实例
python--正则match_compile_search_findall用法
Python全栈--6.1-match-search-findall-group(s)的区别以及计算器实例