作为算法工程师,python是我们的好朋友,python的正则模块更是我们锋利的小匕首,处理起文本来,那是咔咔的。match、search、findall是重要三个方法,搞清楚三者的区别和联系,是每名算法工程师的必备基础。
下面的讲解,使用先提出要点,再用例子说明的方法。所以,如果看到要点,不是很懂,没关系,后面都有具体的例子的。
match
首先来看一下文档中的说明:
If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern;
match方法有两点需要单独注意:
1、它只从字符串最开始的地方进行匹配; 2、它只匹配第一行 3、子group如果有多个匹配,只匹配最后一个
我们看下面的代码:

因为match只从字符串开头进行匹配,所以上面的代码返回了None,也就是没有匹配到。
再看下面的代码:

字符串第二行的开头是abc,但是因为match只匹配第一行,所以还是没匹配到。
有人说,我使用re.M(MULTILINE)标志是不是就可以了呢?答案是不行,如下所示:

再看下面的代码:

子group (..) 有多个匹配,默认返回最后的匹配。
search
同样,先看一下文档说明,保持良好学习习惯哦!
Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern;
search方法和match相比,有如下需要注意的:
1、在字符串所有位置进行寻找,而不是仅从字符串开头进行寻找
2、如果有多处匹配到,只返回第一个匹配到的
首先看如下代码:

dabc并不是字符串的开头,也匹配到了。
再看下面的代码:

字符串中有两处dabc匹配上,仅匹配了第一个dabc,可以从输出中的span验证这一点。
findall
同样的,先来看一下文档:
Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.
有如下几点需要注意:
1、findall不返回match object,而是返回list 2、如果有pattern中有子group,list中每一项就是子group的元组
请看如下代码:
首先看到,返回的是一个list,第二,每个元素是子group组成的元组。有的小伙伴说,match object 第一个group是整个匹配的pattern,这里怎么没有了?嗯,就是没有了。如果需要,可以这样干:

在整个pattern外面再加一层小括号。
总结
本文详细总结了python常用的match、search、findall的区别与联系。并用具体的例子做了说明,如果觉得不错,点个在看,或者转发个朋友圈,都是很大的支持,谢谢!




