首页 > 编程语言 > 详细

Python中的Re模块

时间:2020-10-18 22:38:37      阅读:27      评论:0      收藏:0      [点我收藏+]

1.首先,re模块是python自带的模块,使用import re就可以使用了

2.基础语法我就不说了。主要进行总结

  match,search都是只匹配一次的。匹配到就返回match对象了。后面是否有可以匹配到的是不管的,如果match开头没有匹配到,返回none,search在整个字符串中么有匹配到返回none

  findall,split返回字符串列表。findall返回匹配到的所有,split以pattern作为分隔符进行分割,并且删除pattern的内容,如果想获取非空的列表,可以while ‘‘ in result:result.remove(‘‘)

import re

# 1-9开头后接5位数字

pattern = r‘[1-9]\d{5}‘

txt = ‘a 123546 is this a s123456123456123456 sda123456 23‘

result = re.split(pattern, txt)

print(result)

while ‘‘ in result:
    result.remove(‘‘)
    
print(result)
###########################
#[‘a ‘, ‘ is this a s‘, ‘‘, ‘‘, ‘ sda‘, ‘ 23‘]
#[‘a ‘, ‘ is this a s‘, ‘ sda‘, ‘ 23‘]

  .sub(pattern,replace,txt)替换,就像notepad里的替换一样,没什么好说的。返回结果是替换后的字符串

技术分享图片

 

Python中的Re模块

原文:https://www.cnblogs.com/liuyongbo/p/13836906.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!