前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python正则表达实战(一)

Python正则表达实战(一)

作者头像
TalkPython
发布2021-05-28 17:24:42
3520
发布2021-05-28 17:24:42
举报
文章被收录于专栏:TalkPythonTalkPython
1、检查给定字符串中,是否包含某个字符串
代码语言:javascript
复制
>>> line1 = 'start address: 0xA0, func1 address: 0xC0'
>>> line2 = 'end address: 0xFF, func2 address: 0xB0'

>>> bool(re.search(r'0xB0', line1))     
False
>>> bool(re.search(r'0xB0', line2))     
True
2、替换给定字符串中,指定的所有字符
代码语言:javascript
复制
>>> ip = 'They ate 5 apples and 5 oranges'

>>> re.sub(r'5','five',ip)        
'They ate five apples and five oranges'
3、过滤出列表中不包含字母e的元素
代码语言:javascript
复制
>>> items = ['goal', 'new', 'user', 'sit', 'eat', 'dinner']

>>> [w for w in items if not re.search(r'e',w)]        
['goal', 'sit']
4、不区分大小写,将给定字符中的note,全部替换为X
代码语言:javascript
复制
>>> ip = 'This note should not be NoTeD'

>>> re.sub(r'note','X',ip,flags=re.I)        
'This X should not be XD'
5、不区分大小写,将给定内容中所有包含字符串start的行去掉
代码语言:javascript
复制
>>> para = '''good start
... Start working on that
... project you always wanted
... stars are shining brightly
... hi there
... start and try to
... finish the book
... bye'''

>>> pat = re.compile(r'start',flags=re.I)      
>>> for line in para.split('\n'):
...     if not pat.search(line):
...         print(line)
... 
project you always wanted
stars are shining brightly
hi there
finish the book
bye
6、给定一个列表,找出列表中包含字母a或者w的字符串
代码语言:javascript
复制
>>> items = ['goal', 'new', 'user', 'sit', 'eat', 'dinner']

>>> [w for w in items if re.search(r'a',w) or re.search(r'w',w)]
['goal', 'new', 'eat']
7、给定一个列表,找出列表中包含字母e和n的字符串
代码语言:javascript
复制
>>> items = ['goal', 'new', 'user', 'sit', 'eat', 'dinner']

>>> [w for w in items if re.search(r'e',w) and re.search(r'n',w)]
['new', 'dinner']
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-05-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 TalkPython 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、检查给定字符串中,是否包含某个字符串
  • 2、替换给定字符串中,指定的所有字符
  • 3、过滤出列表中不包含字母e的元素
  • 4、不区分大小写,将给定字符中的note,全部替换为X
  • 5、不区分大小写,将给定内容中所有包含字符串start的行去掉
  • 6、给定一个列表,找出列表中包含字母a或者w的字符串
  • 7、给定一个列表,找出列表中包含字母e和n的字符串
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档