Установка:
$ pip install globre
Использование:
import globre
names = [
'/path/to/file.txt',
'/path/to/config.ini',
'/path/to/subdir/base.ini',
]
txt_names = [name for name in names if globre.match('/path/to/*.txt', name)]
assert txt_names == ['/path/to/file.txt']
ini_names = [name for name in names if globre.match('/path/to/*.ini', name)]
assert ini_names == ['/path/to/config.ini']
all_ini_names = [name for name in names if globre.match('/path/to/**.ini', name)]
assert all_ini_names == ['/path/to/config.ini', '/path/to/subdir/base.ini']
Детали:
Этот пакет позволяет проверять соответствие Python-строки шаблонам, подобным используемым в командной строке Unix-систем. Большинство символов совпадают только с самими собой, кроме следующих специальных последовательностей:
Sequence |
Meaning |
? |
Matches any single character except the slash ('/') character. |
* |
Matches zero or more characters excluding the slash ('/') character, e.g. /etc/*.conf which will not match "/etc/foo/bar.conf". |
** |
Matches zero or more characters including the slash ('/') character, e.g. /lib/**.so which will match "/lib/foo/bar.so". |
\ |
Escape character used to precede any of the other special characters (in order to match them literally), e.g. foo\? will match "foo" followed by a literal question mark. |
[...] |
Matches any character in the specified regex-style character range, e.g. foo[0-9A-F].conf. |
{...} |
Inlines a regex expression, e.g. foo-{\\D{2,4\}}.txt which will match "foo-bar.txt" but not "foo-012.txt". |