Skip to content
Advertisement

Efficient regex with lists

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

JavaScript

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

JavaScript

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

JavaScript

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

Advertisement

Answer

I usually do:

JavaScript

Or just

JavaScript

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