免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 15003 | 回复: 6
打印 上一主题 下一主题

re.compile是做什么用的啊?好像没有他也一样哦 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-04-02 14:42 |只看该作者 |倒序浏览
好像用不用它输出的结果都一样,用了re.compile有什么好处呢
  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. import re

  4. content = "l love you world"
  5. a1 = re.findall(r'love(.*)world',content)
  6. print a1

  7. pattern = re.compile(r'love(.*)world')
  8. a2 = re.findall(pattern,content)
  9. print a2
复制代码

论坛徽章:
0
2 [报告]
发表于 2010-04-02 15:57 |只看该作者
回复 1# 盖茨他爹


    re.compile是指用变量代表 正则表达式,你可以不必重复输入 相同的 正则 表达式。

论坛徽章:
0
3 [报告]
发表于 2010-04-02 16:25 |只看该作者
用变量代替正则表达式可以这样啊
import re

content = "l love you world"
pattern = r'love(.*)world'      #这行可以不用re.compile
a1 = re.findall(pattern,content)
print a1

论坛徽章:
0
4 [报告]
发表于 2010-04-02 17:18 |只看该作者
用变量代替正则表达式可以这样啊
import re

content = "l love you world"
pattern = r'love(.*)world ...
盖茨他爹 发表于 2010-04-02 16:25



    你试试,正则里包括 定义过的正则 变量。sub('love|pattern'.........

论坛徽章:
0
5 [报告]
发表于 2010-04-02 17:58 |只看该作者
这都是什么解释啊.不能看看文档么?
but using re.compile() and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program.

论坛徽章:
0
6 [报告]
发表于 2010-04-03 00:41 |只看该作者
明白了,re.compile是对规则进行预编译以提速,谢谢楼上,谢谢2楼和4楼的朋友

论坛徽章:
0
7 [报告]
发表于 2015-08-04 10:44 |只看该作者
  1. >>> import re
  2. >>> content = "l love you world"
  3. >>> pattern = r'love(.*)world'
  4. >>> pattern.search(content)
  5. Traceback (most recent call last):
  6.   File "<pyshell#3>", line 1, in <module>
  7.     pattern.search(content)
  8. AttributeError: 'str' object has no attribute 'search'
  9. >>> pattern = re.compile(r'love(.*)world')
  10. >>> pattern.search(content)
  11. <_sre.SRE_Match object; span=(2, 16), match='love you world'>
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP