使用正则表达式过滤列表 [英] Filter list with regex
本文介绍了使用正则表达式过滤列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我认为这是一项简单的任务,但我是正则表达式的新手,所以无法弄清楚.我想过滤一个包含以下内容的列表:ANY"-ANY"-ANY"
I think this is a easy task but I'm new to regex so can't figure it out. I want to filter a list that contains something like this: "ANY"-"ANY"-"ANY"
输入:
List1 = ["AB.22-01-01", "AB.33-01-44", "--4", "AA.44--05", "--"]
输出:
List2 = ["AB.22-01-01", "AB.33-01-44"]
每个项目将包含两个-",但我只想获取-"两侧带有文本的项目.
Each item will contain two "-" but I only want to get the ones with text on each sides of the "-".
推荐答案
尝试使用 re模块:
import re
p = re.compile('^.+-.+-.+$')
l1 = ["AB.22-01-01", "AB.33-01-44", "--4", "AA.44--05", "--"]
l2 = [ s for s in l1 if p.match(s) ]
这篇关于使用正则表达式过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文