regular expression usage in glob.glob for python

前端 未结 4 627
我在风中等你
我在风中等你 2020-11-27 05:38
import glob

list = glob.glob(r\'*abc*.txt\') + glob.glob(r\'*123*.txt\') + glob.glob(r\'*a1b*.txt\')

for i in list:
  print i

This code works to

4条回答
  •  遥遥无期
    2020-11-27 06:25

    I'm surprised that no answers here used filter.

    import os
    import re
    
    def glob_re(pattern, strings):
        return filter(re.compile(pattern).match, strings)
    
    filenames = glob_re(r'.*(abc|123|a1b).*\.txt', os.listdir())
    

    This accepts any iterator that returns strings, including lists, tuples, dicts(if all keys are strings), etc. If you want to support partial matches, you could change .match to .search. Please note that this obviously returns a generator, so if you want to use the results without iterating over them, you could convert the result to a list yourself, or wrap the return statement with list(...).

提交回复
热议问题