python中的match_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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值