filter strings by regex in a list
Question: I'd like to filter a list of strings in python by using regex. In the
following case, keeping only the files with a '.npy' extension.

The code that doesn't work:

    
    
    import re
    
    files = [ '/a/b/c/la_seg_x005_y003.png',
              '/a/b/c/la_seg_x005_y003.npy',
              '/a/b/c/la_seg_x004_y003.png',
              '/a/b/c/la_seg_x004_y003.npy',
              '/a/b/c/la_seg_x003_y003.png',
              '/a/b/c/la_seg_x003_y003.npy', ]
    
    regex = re.compile(r'_x\d+_y\d+\.npy')
    
    selected_files = filter(regex.match, files)
    print(selected_files)
    

The same regex works for me in Ruby:

    
    
    selected = files.select { |f| f =~ /_x\d+_y\d+\.npy/ }
    

What's wrong with the Python code?


Answer: Just use `search`\- since match starts matching from the beginning to end
(i.e. entire) of string and search matches anywhere in the string.

    
    
    import re
    
    files = [ '/a/b/c/la_seg_x005_y003.png',
              '/a/b/c/la_seg_x005_y003.npy',
              '/a/b/c/la_seg_x004_y003.png',
              '/a/b/c/la_seg_x004_y003.npy',
              '/a/b/c/la_seg_x003_y003.png',
              '/a/b/c/la_seg_x003_y003.npy', ]
    
    regex = re.compile(r'_x\d+_y\d+\.npy')
    
    selected_files = filter(regex.search, files)
    print(selected_files)
    

Output-

    
    
    ['/a/b/c/la_seg_x005_y003.npy', '/a/b/c/la_seg_x004_y003.npy', '/a/b/c/la_seg_x003_y003.npy']
    

