python学习【第三天】正则表达式re模块

re.match函数

re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。

re.match(pattern, string, flags=0)

#re模块
import re
print(re.match('www', 'www.baidu.com  www').span())  # 在起始位置匹配
print(re.match('www', 'www.baidu.com  www'))
print(re.match('com', 'www.baidu.com  com'))         # 不在起始位置匹配
#(0, 3)
#<re.Match object; span=(0, 3), match='www'>
#None

#!/usr/bin/python3
import re
 
line = "Cats are smarter than dogs"
# .* 表示任意匹配除换行符(\n、\r)之外的任何单个或多个字符
matchObj = re.match( '(.*) are (.*?) .*', line, re.M|re.I)
print(matchObj) 
if matchObj:
   print ("matchObj.group() : ", matchObj.group())
   print ("matchObj.group(1) : ", matchObj.group(1))
   print ("matchObj.group(2) : ", matchObj.group(2))
   print ("matchObj.group(0) : ", matchObj.group(0))
   print ("matchObj.groups() : ", matchObj.groups())
   print ("matchObj.groups(1) : ", matchObj.groups(1))
   print ("matchObj.groups(3) : ", matchObj.groups(3))
else:
   print ("No match!!")
'''<re.Match object; span=(0, 26), match='Cats are smarter than dogs'>
matchObj.group() :  Cats are smarter than dogs
matchObj.group(1) :  Cats
matchObj.group(2) :  smarter
matchObj.group(0) :  Cats are smarter than dogs
matchObj.groups() :  ('Cats', 'smarter')
matchObj.groups(1) :  ('Cats', 'smarter')
matchObj.groups(3) :  ('Cats', 'smarter')'''

re.search方法

re.search 扫描整个字符串并返回第一个成功的匹配。

re.search(pattern, string, flags=0)
#!/usr/bin/python3
 
import re
 
print(re.search('www', 'www.baidu.com').span())  # 在起始位置匹配
print(re.search('com', 'www.baidu.com').span())         # 不在起始位置匹配
#(0, 3)
#(10, 13)
#!/usr/bin/python3
 
import re
 
line = "Cats are smarter than dogs";
 
searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
print(searchObj) 
if searchObj:
   print ("searchObj.group() : ", searchObj.group())
   print ("searchObj.group(1) : ", searchObj.group(1))
   print ("searchObj.group(2) : ", searchObj.group(2))
else:
   print ("Nothing found!!")
'''<re.Match object; span=(0, 26), match='Cats are smarter than dogs'>
searchObj.group() :  Cats are smarter than dogs
searchObj.group(1) :  Cats
searchObj.group(2) :  smarter'''

检索和替换

Python 的re模块提供了re.sub用于替换字符串中的匹配项。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值