Skip to content
Advertisement

Efficient regex with lists

I have a list of strings coming from os.listdir() that looks like the following:

['foo',
 'bar'
 'backup_20180406'
 ...]

out of those entries, I wanna get the ones that match the “backup_YYYYMMDD” pattern. The regex for that, with named groups, would be

regex = r"BACKUP_(?P<date>d+)"

I am trying to create a list that contains the date only from the above (aka the .group('date')), but I cannot find a way to do it without parsing the strings twice..

res = [re.search(regex, x).group('date') for x in filter(r.match, os.listdir(folder))]

I am sure that I am missing something really obvious and concise here, so is there a better way?

Advertisement

Answer

I usually do:

regex = re.compile(r"BACKUP_(?P<date>d+)")
a = ['foo', "BACKUP_20180406", 'xxx']
matches = [regex.match(x) for x in a]
valid = [x.group('date') for x in matches if x]

Or just

valid = [x.group('date') for x in (regex.match(y) for y in a) if x]

Also notice that regex.match is much faster than regex.search when applicable – i.e. when you search from the beginning of the line.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement