re.search()方法扫描整个字符串,并返回第一个成功的匹配。如果匹配失败,则返回None。
与re.match()方法不同,re.match()方法要求必须从字符串的开头进行匹配,如果字符串的开头不匹配,整个匹配就失败了;
re.search()并不要求必须从字符串的开头进行匹配,也就是说,正则表达式可以是字符串的一部分。
1
|
re.search(pattern, string, flags = 0 ) |
- pattern : 正则中的模式字符串。
- string : 要被查找替换的原始字符串。
- flags : 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。
例1:
1
2
3
4
5
6
7
8
9
|
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:只匹配数字
1
2
3
4
5
6
7
8
9
|
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
举例说明:
1
2
|
import re print (re.match( 'super' , 'superstition' ).span()) |
(0, 5)
1
|
print (re.match( 'super' , 'insuperable' )) |
None
1
|
print (re.search( 'super' , 'superstition' ).span()) |
(0, 5)
1
|
print (re.search( 'super' , 'insuperable' ).span()) |
(2, 7)
到此这篇关于Python3 re.search()方法的具体使用的文章就介绍到这了,更多相关Python3 re.search()内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/m0_37360684/article/details/84140403