更多课程 选择中心


Python培训

400-111-8989

Python re 模块中match, search ,findall的区别


1. match

从字符串的第一个字符开始匹配,如果没有匹配到就会返回None,匹配到的话则会返回一个Match Object,获取值得方法是group()

Python

import re

source = 'https://www.baidu.com'# Match 'www', the output is Noneprint(re.match('www', source))# Match 'http', the output is 'http'print(re.match('http', source).group())

2. search

搜索整个字符串,直到配到第一个对象后就会返回Match Object,否则返回None,获取值的方法同样是group()

Python

import re

source = 'https://www.baidu.com'# Search 'www', the output is Noneprint(re.match('zzz', source))# Search 'http', stop at the first match, the output is 'http'print(re.match('http', source).group())

3. findall

这个方法会返回字符串中所有符合匹配条件的对象,并且以list的形式返回。如果没有匹配到则返回一个空的list,这一点和上面两个不同。

Python

import re

source = 'https://www.baidu.com'# Find all 'www', output is [], which is an empty listprint(re.findall('zzz', source))# Find all 'w', output is ['w', 'w', 'w']print(re.findall('w', source))

4. compile

re.compile是将正则表达式转换为模式对象,这样可以更加有效率地匹配。使用compile进行一次转换后,之后每次再使用这样的模式的时候就不需要再进行compile,可以直接使用之前转换过的对象。

Python

import re

source = 'https://www.baidu.com'# Get a compiled pattern for usepattern = re.compile('baidu')print(re.findall(pattern, source))

5. 贪婪匹配(Greedy)

正则表达式默认是贪婪匹配,顾名思义,就是匹配到尽可能多的字符,加入说你想匹配到某个特定的字符就停止,那么不能使用贪婪匹配。两种模式切换的关键字是 '?',具体看一下下面的代码。

Python

import re

source = 'come home'# Greedy regex, the output is ['come home']pattern1 = re.compile('c.*e')print(re.findall(pattern1, source))# Non-greedy regex, the output is ['come']pattern2 = re.compile('c.*?e')print(re.findall(pattern2, source))

预约申请免费试听课

填写下面表单即可预约申请免费试听! 怕学不会?助教全程陪读,随时解惑!担心就业?一地学习,可全国推荐就业!

上一篇:30分钟学会用Python编写简单程序
下一篇:学习Python有哪些书籍?这里有一份书单送给你

2021年Python全套免费视频教程在哪里?

人工智能与语音遥控的区别?

Python和C语言的区别?

Python数据分析的几种方法及原理?

  • 扫码领取资料

    回复关键字:视频资料

    免费领取 达内课程视频学习资料

Copyright © 2023 Tedu.cn All Rights Reserved 京ICP备08000853号-56 京公网安备 11010802029508号 达内时代科技集团有限公司 版权所有

选择城市和中心
黑龙江省

吉林省

河北省

湖南省

贵州省

云南省

广西省

海南省