Python中的Re模块


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里的替换一样,没什么好说的。返回结果是替换后的字符串

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM