您现在的位置是:网站首页> 编程资料编程资料
Python3 re.search()方法的具体使用_python_
2023-05-26
350人已围观
简介 Python3 re.search()方法的具体使用_python_
re.search()方法扫描整个字符串,并返回第一个成功的匹配。如果匹配失败,则返回None。
与re.match()方法不同,re.match()方法要求必须从字符串的开头进行匹配,如果字符串的开头不匹配,整个匹配就失败了;
re.search()并不要求必须从字符串的开头进行匹配,也就是说,正则表达式可以是字符串的一部分。
re.search(pattern, string, flags=0)
- pattern : 正则中的模式字符串。
- string : 要被查找替换的原始字符串。
- flags : 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。
例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
match()和search()的区别:
- match()函数只检测RE是不是在string的开始位置匹配,
- search()会扫描整个string查找匹配
- match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none
举例说明:
import re print(re.match('super', 'superstition').span()) (0, 5)
print(re.match('super','insuperable')) None
print(re.search('super','superstition').span()) (0, 5)
print(re.search('super','insuperable').span()) (2, 7)
到此这篇关于Python3 re.search()方法的具体使用的文章就介绍到这了,更多相关Python3 re.search()内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关内容
- Python读取xlsx文件报错:xlrd.biffh.XLRDError: Excel xlsx file;not supported问题解决_python_
- pandas中df.rename()的具体使用_python_
- pandas 修改列名的实现示例_python_
- python读取和保存为excel、csv、txt文件及对DataFrame文件的基本操作指南_python_
- 详解django中视图函数的FBV和CBV_python_
- pycharm创建并使用虚拟环境的详细图文教程_python_
- conda创建环境、安装包、删除环境步骤详细记录_python_
- python使用pandas读写excel文件的方法实例_python_
- YOLOv5改进之添加SE注意力机制的详细过程_python_
- pyinstaller打包python3.6和PyQt5中各种错误的解决方案汇总_python_
