Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard list matching in python

Tags:

python

I have a list of strings

l = [
   '/api/users/*',
   '/api/account/*
]

And paths are like

/api/users/add/
/api/users/edit/1
/api/users/
/api/account/view/1
/api/account/

How can I perform filter for the paths if they exist in the list l.

condition like

'/api/users/add/' in l

should return True and for all given paths above.

like image 407
Anuj TBE Avatar asked Mar 04 '23 12:03

Anuj TBE


1 Answers

If I understand correctly, you want to see if the wildcard pattern would hold true. For this you can use the fnmatch module from glob. Supposing you have this:

l = [
   '/api/users/*',
   '/api/account/*'
]

paths = [
   '/api/users/add/'
   '/api/users/edit/1',
   '/api/users/',
   '/api/account/view/1',
   '/api/account/',
   '/non/existent/path'
]

You could get this:

>>> import fnmatch
>>> [any(fnmatch.fnmatch(path, pat) for pat in l) for path in paths]
[True, True, True, True, False]
like image 181
Bob Zimmermann Avatar answered Apr 19 '23 09:04

Bob Zimmermann