search() 和 match() 的区别
import re
text_1 = 'This is a text.'
text_2 = 'is this a text?'
print('文本:',text_1,';方法:match()',';结果:',re.match('is',text_1))
print('文本:',text_1,';方法:search()',';结果:',re.search('is',text_1))
print('-'*100)
print('文本:',text_2,';方法:match()',';结果:',re.match('is',text_2))
print('文本:',text_2,';方法:search()',';结果:',re.search('is',text_2))
结果:
文本: This is a text. ;方法:match() ;结果: None
文本: This is a text. ;方法:search() ;结果: <_sre.SRE_Match object; span=(2, 4), match='is'>
--------------------------------------------------------------------------------------------
文本: is this a text? ;方法:match() ;结果: <_sre.SRE_Match object; span=(0, 2), match='is'>
文本: is this a text? ;方法:search() ;结果: <_sre.SRE_Match object; span=(0, 2), match='is'>
** match() 函数只检测字符串的开始部分是否匹配, search() 会扫描整个字符串查找匹配;也就是说 match() 只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话, match() **就返回none。