第十次python笔记

本文介绍了Python中正则表达式的方法,包括match()、search()、findall()用于字符串搜索和查找,以及sub()、subn()用于字符串替换。通过实例展示了如何查找特定模式的单词以及进行替换操作,是理解Python正则表达式操作的重要参考。
摘要由CSDN通过智能技术生成

使用正则表达式对象

1.match()、search()、findall()

match(string[, pos[, endpos]])方法在字符串开头或指定位置进行搜索,模式必须出现在字符串开头或指定位置;

search(string[, pos[, endpos]])方法在整个字符串或指定范围中进行搜索;

findall(string[, pos[, endpos]])方法在字符串指定范围中查找所有符合正则表达式的字符串并以列表形式返回。

>>> import re
>>> example = 'ShanDong Institute of Business and Technology'
>>> pattern = re.compile(r'\bB\w+\b')  #查找以B开头的单词
>>> pattern.findall(example)   #使用正则表达式对象的findall()方法
['Business']
>>> pattern = re.compile(r'\w+g\b')    #查找以字母g结尾的单词
>>> pattern.findall(example)
['ShanDong']
>>> pattern = re.compile(r'\b[a-zA-Z]{3}\b')#查找3个字母长的单词
>>> pattern.findall(example)
['and']
>>> s = 'ab134ab98723jafjweoruiagab'
>>> m = re.search(r'((ab).*){2}.*(ab)', s)#在s中查找ab的第3次出现
>>> m.group(3)
'ab'
>>> m.span(3)
(24, 26)
>>> s[24:]
'ab'
>>> pattern.match(example)     #从字符串开头开始匹配,失败返回空值
>>> pattern.search(example)    #在整个字符串中搜索,成功
<_sre.SRE_Match object; span=(31, 34), match='and'>
>>> pattern = re.compile(r'\b\w*a\w*\b') #查找所有含有字母a的单词
>>> pattern.findall(example)
['ShanDong', 'and']
>>> text = "He was carefully disguised but captured quickly by police."
>>> re.findall(r"\w+ly", text) #查找所有以字母组合ly结尾的单词
['carefully', 'quickly']

2.sub()、subn()

正则表达式对象的sub(repl, string[, count = 0])和subn(repl, string[, count = 0])方法用来实现字符串替换功能,其中参数repl可以为字符串或返回字符串的可调用对象。

>>> pattern = re.compile(r'\bb\w*\b', re.I) #匹配以b或B开头的单词
>>> print(pattern.sub('*', example))    #将符合条件的单词替换为*
>>>> print(pattern.sub(lambda x: x.group(0).upper(), example))
                                     #把所有匹配项都改为大写
>>> print(pattern.sub('*', example, 1))      #只替换1次
>>> pattern = re.compile(r'\bb\w*\b')   #匹配以字母b开头的单词
>>> print(pattern.sub('*', example, 1)) #将符合条件的单词替换为*
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值