标签:python
匹配搜索 match,search,findall区别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‘
re.search(r‘de‘,‘8ugde‘).group()
‘de‘
re.search(r‘de‘,‘de8ug‘).group()
‘de‘
re.search(‘de‘,‘8ugde 88deug‘).group()
‘de‘
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‘
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
标签:python
原文地址:http://blog.51cto.com/13587169/2128240