glob.py 893 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import re
  2. def translate(pattern):
  3. r"""
  4. Given a glob pattern, produce a regex that matches it.
  5. >>> translate('*.txt')
  6. '[^/]*\\.txt'
  7. >>> translate('a?txt')
  8. 'a.txt'
  9. >>> translate('**/*')
  10. '.*/[^/]*'
  11. """
  12. return ''.join(map(replace, separate(pattern)))
  13. def separate(pattern):
  14. """
  15. Separate out character sets to avoid translating their contents.
  16. >>> [m.group(0) for m in separate('*.txt')]
  17. ['*.txt']
  18. >>> [m.group(0) for m in separate('a[?]txt')]
  19. ['a', '[?]', 'txt']
  20. """
  21. return re.finditer(r'([^\[]+)|(?P<set>[\[].*?[\]])|([\[][^\]]*$)', pattern)
  22. def replace(match):
  23. """
  24. Perform the replacements for a match from :func:`separate`.
  25. """
  26. return match.group('set') or (
  27. re.escape(match.group(0))
  28. .replace('\\*\\*', r'.*')
  29. .replace('\\*', r'[^/]*')
  30. .replace('\\?', r'.')
  31. )