Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter list with regex [duplicate]

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"

Input:

List1 = ["AB.22-01-01", "AB.33-01-44", "--4", "AA.44--05", "--"]

Output:

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 "-".

like image 496
Harila Avatar asked Nov 27 '15 15:11

Harila


2 Answers

Try this using re module :

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) ]
like image 197
Eric Citaire Avatar answered Nov 04 '22 07:11

Eric Citaire


You can use a regular expressions. It will return all element that don't contains --

>>> import re
>>> pat = re.compile(r'^((?!--).)*$')
>>> [i for i in List1 if pat.match(i)]
['AB.22-01-01', 'AB.33-01-44']

Demo

like image 2
styvane Avatar answered Nov 04 '22 09:11

styvane