python – 在列表中通过正则表达式过滤字符串
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 在列表中通过正则表达式过滤字符串,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1551字,纯文字阅读大概需要3分钟。
内容图文
![python – 在列表中通过正则表达式过滤字符串](/upload/InfoBanner/zyjiaocheng/709/138419b8611e4a03bc797a9600df57ac.jpg)
我想使用正则表达式过滤python中的字符串列表.在以下情况中,仅保留扩展名为“.npy”的文件.
代码不起作用:
import re
files = [ '/a/b/c/la_seg_x005_y003.png',
'/a/b/c/la_seg_x005_y003.npy',
'/a/b/c/la_seg_x004_y003.png',
'/a/b/c/la_seg_x004_y003.npy',
'/a/b/c/la_seg_x003_y003.png',
'/a/b/c/la_seg_x003_y003.npy', ]
regex = re.compile(r'_x\d+_y\d+\.npy')
selected_files = filter(regex.match, files)
print(selected_files)
同样的正则表达式在Ruby中适用于我:
selected = files.select { |f| f =~ /_x\d+_y\d+\.npy/ }
Python代码有什么问题?
解决方法:
selected_files = filter(regex.match, files)
re.match('regex')等于re.search(‘^ regex’)或text.startswith(‘regex’)但是正则表达式版本.它只检查字符串是否以正则表达式开头.
所以,使用re.search()代替:
import re
files = [ '/a/b/c/la_seg_x005_y003.png',
'/a/b/c/la_seg_x005_y003.npy',
'/a/b/c/la_seg_x004_y003.png',
'/a/b/c/la_seg_x004_y003.npy',
'/a/b/c/la_seg_x003_y003.png',
'/a/b/c/la_seg_x003_y003.npy', ]
regex = re.compile(r'_x\d+_y\d+\.npy')
selected_files = list(filter(regex.search, files))
# The list call is only required in Python 3, since filter was changed to return a generator
print(selected_files)
输出:
['/a/b/c/la_seg_x005_y003.npy',
'/a/b/c/la_seg_x004_y003.npy',
'/a/b/c/la_seg_x003_y003.npy']
如果您只想获取所有.npy文件,只需使用str.endswith():
files = [ '/a/b/c/la_seg_x005_y003.png',
'/a/b/c/la_seg_x005_y003.npy',
'/a/b/c/la_seg_x004_y003.png',
'/a/b/c/la_seg_x004_y003.npy',
'/a/b/c/la_seg_x003_y003.png',
'/a/b/c/la_seg_x003_y003.npy', ]
selected_files = list(filter(lambda x: x.endswith('.npy'), files))
print(selected_files)
内容总结
以上是互联网集市为您收集整理的python – 在列表中通过正则表达式过滤字符串全部内容,希望文章能够帮你解决python – 在列表中通过正则表达式过滤字符串所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。