Python中请不要再用re.compile了

作者:青南 时间:2021-08-30 23:57:51 

前言

如果大家在网上搜索Python 正则表达式,你将会看到大量的垃圾文章会这样写代码:


import re

pattern = re.compile('正则表达式')
text = '一段字符串'
result = pattern.findall(text)

这些文章的作者,可能是被其他语言的坏习惯影响了,也可能是被其他垃圾文章误导了,不假思索拿来就用。

在Python里面,真的不需要使用re.compile!

为了证明这一点,我们来看Python的源代码。

在PyCharm里面输入:


import re

re.search

然后Windows用户按住键盘上的Ctrl键,鼠标左键点击search,Mac用户按住键盘上的Command键,鼠标左键点击search,PyCharm会自动跳转到Python的re模块。在这里,你会看到我们常用的正则表达式方法,无论是findall还是search还是sub还是match,全部都是这样写的:


_compile(pattern, flag).对应的方法(string)

例如:


def findall(pattern, string, flags=0):
"""Return a list of all non-overlapping matches in the string.

If one or more capturing 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."""
return _compile(pattern, flags).findall(string)

如下图所示:

Python中请不要再用re.compile了

然后我们再来看compile:


def compile(pattern, flags=0):
"Compile a regular expression pattern, returning a Pattern object."
return _compile(pattern, flags)

如下图所示:

Python中请不要再用re.compile了

看出问题来了吗?

我们常用的正则表达式方法,都已经自带了compile了!

根本没有必要多此一举先re.compile再调用正则表达式方法。

此时,可能会有人反驳:

如果我有一百万条字符串,使用使用某一个正则表达式去匹配,那么我可以这样写代码:


texts = [包含一百万个字符串的列表]
pattern = re.compile('正则表达式')
for text in texts:
pattern.search(text)

这个时候,re.compile只执行了1次,而如果你像下面这样写代码:


texts = [包含一百万个字符串的列表]
for text in texts:
re.search('正则表达式', text)

相当于你在底层对同一个正则表达式执行了100万次re.compile。

Talk is cheap, show me the code.

我们来看源代码,正则表达式re.compile调用的是_compile,我们就去看_compile的源代码,如下图所示:

红框中的代码,说明了_compile自带缓存。它会自动储存最多512条由type(pattern), pattern, flags)组成的Key,只要是同一个正则表达式,同一个flag,那么调用两次_compile时,第二次会直接读取缓存。

综上所述,请你不要再手动调用re.compile了,这是从其他语言(对的,我说的就是Java)带过来的陋习。

来源:https://juejin.im/post/5d144231f265da1bb67a2a29

标签:python,re.compile
0
投稿

猜你喜欢

  • 使table也能overflow:hidden

    2008-08-18 21:04:00
  • Python通用验证码识别OCR库之ddddocr验证码识别

    2021-05-16 22:55:00
  • Python OpenCV 调用摄像头并截图保存功能的实现代码

    2022-07-08 03:11:13
  • Tensorflow之MNIST CNN实现并保存、加载模型

    2023-10-16 06:21:33
  • 部署.Net6项目到docker

    2024-06-05 15:43:46
  • laravel 实现阿里云oss文件上传功能的示例

    2023-06-13 20:39:26
  • Python 3.10 中 6 个兴奋的新特性

    2021-02-21 03:30:26
  • PHP simplexml_load_file()函数讲解

    2023-06-03 23:16:56
  • python在新的图片窗口显示图片(图像)的方法

    2021-11-17 00:38:18
  • Python编程基础之字典

    2021-10-02 13:34:56
  • MHTML在ie7/vista bug 解决方案

    2010-02-01 12:42:00
  • SqlServer提示“列前缀tempdb.无效: 未指定表名”问题解决方案

    2024-01-14 04:39:41
  • PyTorch CUDA环境配置及安装的步骤(图文教程)

    2022-06-19 14:00:28
  • Python解析多帧dicom数据详解

    2022-08-13 21:16:13
  • Mysql全局ID生成方法

    2023-07-02 13:59:53
  • python去除文件中重复的行实例

    2022-07-30 17:33:38
  • Python一行代码实现生成和读取二维码

    2023-04-30 15:31:18
  • mysql 加了 skip-name-resolve不能链接数据库问题的解决方法

    2024-01-24 11:43:49
  • pandas取dataframe特定行列的实现方法

    2022-03-05 15:51:29
  • Python中return用法案例详解

    2022-09-09 10:35:40
  • asp之家 网络编程 m.aspxhome.com