python 中 re.match和re.search()函数

发布时间 2023-05-31 13:10:06作者: 小鲨鱼2018

 

两者都返回首次匹配字符串的索引,re.match函数只从头开始匹配, re.search函数不限制只从头开始匹配。

001、re.match函数

[root@PC1 test2]# python3
Python 3.10.9 (main, Mar  1 2023, 18:23:06) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import re                                   ## 导入模块
>>> str1="abcdef"
>>> re.match("ab", str1)                        ## 返回索引0,2
<re.Match object; span=(0, 2), match='ab'>
>>> re.match("bc", str1)                        ## 不能从中间匹配

 

002、re.search函数

>>> import re
>>> str1="abcdefg"
>>> re.search("ab", str1)
<re.Match object; span=(0, 2), match='ab'>
>>> re.search("bc", str1)
<re.Match object; span=(1, 3), match='bc'>     ## re.search不限制只从开头匹配