Search code examples
pythonregexfilenamesgitignorefnmatch

.gitignore style fnmatch()


What would be the simplest way to have .gitignore style fnmatch() with Python. Looks like that stdlib does not provide a match() function which would match a path spec against an UNIX style path regex.

.gitignore have both paths and files with wildcards to be (black)listed


Solution

  • If you want to use mixed UNIX wildcard patterns as listed in your .gitignore example, why not just take each pattern and use fnmatch.translate with re.search?

    import fnmatch
    import re
    
    s = '/path/eggs/foo/bar'
    pattern = "eggs/*"
    
    re.search(fnmatch.translate(pattern), s)
    # <_sre.SRE_Match object at 0x10049e988>
    

    translate turns the wildcard pattern into a re pattern

    Hidden UNIX files:

    s = '/path/to/hidden/.file'
    isHiddenFile = re.search(fnmatch.translate('.*'), s)
    if not isHiddenFile:
        # do something with it