Python glob but against a list of strings rather than the filesystem

后端 未结 9 1764
被撕碎了的回忆
被撕碎了的回忆 2021-02-06 21:24

I want to be able to match a pattern in glob format to a list of strings, rather than to actual files in the filesystem. Is there any way to do this, or convert a glob

9条回答
  •  执笔经年
    2021-02-06 21:38

    While fnmatch.fnmatch can be used directly to check whether a pattern matches a filename or not, you can also use the fnmatch.translate method to generate the regex out of the given fnmatch pattern:

    >>> import fnmatch
    >>> fnmatch.translate('*.txt')
    '.*\\.txt\\Z(?ms)'
    

    From the documenation:

    fnmatch.translate(pattern)

    Return the shell-style pattern converted to a regular expression.

提交回复
热议问题