re.search()方法扫描整个字符串,并返回第一个成功的匹配。如果匹配失败,则返回None。
与re.match()方法不同,re.match()方法要求必须从字符串的开头进行匹配,如果字符串的开头不匹配,整个匹配就失败了;
re.search()并不要求必须从字符串的开头进行匹配,也就是说,正则表达式可以是字符串的一部分。
re.search(pattern, string, flags=0)
例1:
import re content = 'Hello 123456789 Word_This is just a test 666 Test' result = re.search('(\d+).*?(\d+).*', content) print(result) print(result.group()) # print(result.group(0)) 同样效果字符串 print(result.groups()) print(result.group(1)) print(result.group(2))
结果:
<_sre.SRE_Match object; span=(6, 49), match='123456789 Word_This is just a test 666 Test'> 123456789 Word_This is just a test 666 Test ('123456789', '666') 123456789 666 Process finished with exit code 0
例2:只匹配数字
import re content = 'Hello 123456789 Word_This is just a test 666 Test' result = re.search('(\d+)', content) print(result) print(result.group()) # print(result.group(0)) 同样效果字符串 print(result.groups()) print(result.group(1))
<_sre.SRE_Match object; span=(6, 15), match='123456789'> 123456789 ('123456789',) 123456789 Process finished with exit code 0
参考:
http://www.runoob.com/python/python-reg-expressions.html
Python3 re.search()方法介绍到这里,更多Python学习 请参考编程字典Python教程 和问答部分,谢谢大家对编程字典的支持。
原文链接:https://blog.csdn.net/m0_37360684/article/details/84140403?ops_request_misc=&request_id=&biz_id=102&utm_term=python&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-9-84140403.nonecase&spm=1018.2226.3001.4187