python之正则表达式(四)

Python的正则表达式(四)
在一般的正则表达式基础上,采用Python的语法规则将正则表达式展现出来。可以通过re模块的以下几个方法来实现:
说明:re模块是Python内置的基本模块,使用时导入即可。
import re 以下的方法全部需导入re模块。
1、match()方法。
功能:用于从字符串的开始处进行匹配,如果在起始位置匹配成功,则返回match对象,否则返回None(关键字)。
re.match(pattern,str,[flags])
pattern:需要查找的字符串。
str:在这个字符串里进行查找。
flags:状态参数,可选。其中re.I代表不区分大小写。

import re
pattern = "w{3}"
str = 'Www.runoob.com'
match = re.match(pattern,str,re.I)
print(match)
print(re.match('com', 'www.runoob.com',re.I))

以上代码返回的就是以下内容。
<re.Match object; span=(0, 3), match=‘Www’>
None
2、search()方法。
功能:用于在整个字符串中所搜第一个匹配的值,如果在起始位置匹配成功,则返回match对象,否则返回None。
格式为:re.search(pattern,str,flags)。

import re
pattern = "w{3}"
str = '123Www.runoob.com'
match = re.search(pattern,str,re.I)
print(match)
print(re.search('com', 'www.runoob.com',re.I))

以上代码返回的结果如下:
<re.Match object; span=(3, 6), match=‘Www’>
<re.Match object; span=(11, 14), match=‘com’>
3、使用findall()方法进行匹配。
findall()方法用于在整个字符串中搜索所有符合正则表达式的字符串,并以列表的形式返回。如果匹配成功,则返回包含匹配结构的列表,否则返回空列表。
语法格式如下:re.findall(pattern,str,[flags])。

import re
pattern = "w{1,}"
str = '123Www.runoob.com,wwwwkkkwwww'
match = re.findall(pattern,str,re.I)
print(match)
print(re.findall('com', 'www.runoob.com',re.I))

以上代码返回以下结果:
[‘Www’, ‘wwww’, ‘wwww’]
[‘com’]

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值