Home > Software engineering >  Python - regex filter to exclude folder for win and linux paths
Python - regex filter to exclude folder for win and linux paths

Time:09-03

I have a list with folders and file paths (example for linux):

res=['./base/folder', './bitbucket ', './output1.txt']
print(res)

So I would like to use filter and regex that will ignore bitbucket folder from this list for further processing. This python script should support paths on both system paths - windows and linux since you are aware of the difference with slashes and backslashes in the paths.

So I made this script but I am not sure if I can define this in one line or multiple lines are needed and how I can support it for both platforms...

import re
.........
.........
res=['./base/folder', './bitbucket ', './output1.txt']
extObjs = filter(None, res)
print(extObjs)
extObjs = filter(lambda x: not re.match(r'.*\/bitbucket', x), extObjs)
for e in extObjs:
    print (e)

What will be the optimal solution to cover this for both OS paths? note: must use regex and filter combination

CodePudding user response:

You might write this in one line using re.search matching either / or \ before it using a character class, and not including empty lines in the result.

import re

res = ['', '   ', './base/folder', './bitbucket ', './output1.txt', '\\bitbucket']
extObjs = filter(lambda s: s.strip() and not re.search(r"[/\\]bitbucket\b", s), res)

print(list(extObjs))

Output

['./base/folder', './output1.txt']

CodePudding user response:

my suggestion is Check the OS first, before filter the path

import platform
import re
system = platform.system()
res=['./base/folder', './bitbucket ', './output1.txt']
extObjs = filter(None, res)
if system == 'Linux':
   extObjs = filter(lambda x: not re.match(r'.*/bitbucket', x), extObjs)
elif system == 'Windows':
   extObjs = filter(lambda x: not re.match(r'.*\bitbucket', x), extObjs)
  • Related