7
votes

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

2
And what regular expressions have you tried? Maybe you don't even need a regular expression. Why not use filter(lambda x: len(x.split('-')) == 3 and all(x.split('-')), List1)? - Maciek

2 Answers

20
votes

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) ]
1
votes

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