python中用re库匹配字符串

正则表达式(re模块)

正则表达式是一种强大的字符串匹配工具,可以用来查找、替换和解析字符串中的模式。Python中的 re 模块提供了对正则表达式的支持,包括 search()match()findall() 等方法。

1.  re.match(pattern, string)  

match(参数1,参数2)

从给定的字符串(参数2)的起始位置搜索匹配指定内容(参数1)。如果找到匹配,则返回匹配对象;如果没有找到匹配,则返回 None

import re

text = "Hello, world!"
match = re.match('Hello', text)
match1=re.match('ell',text)
print(match)   #输出:<re.Match object; span=(0, 5), match='Hello'>
print(match1)  #输出:None

2. re.search(pattern, string) 

search(参数1,参数2)

尝试在给定的字符串(参数2)中匹配指定内容(参数1)。如果找到匹配,则返回匹配对象;如果匹配了多个对象,则返回第一个匹配对象的信息;如果没有找到匹配,则返回 None

import re

text = "Hello, world! wor"


match = re.search('Hello', text)
match1=re.search('wor',text)
match2=re.search('app',text)
print(match)   #输出:<re.Match object; span=(0, 5), match='Hello'>
print(match1)  #输出:<re.Match object; span=(7, 10), match='wor'>
print(match2)  #输出:None

3. re.findall(pattern, string) 

findall(参数1,参数2)

在给定的字符串(参数2)中查找匹配指定内容(参数1)的所有匹配项,并以列表的形式返回。

import re

text = "Hello, world! wor"

match1=re.findall('wor',text)
print(match1)  #输出:['wor', 'wor']

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值