You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

glob.go 644B

12345678910111213141516171819202122232425262728293031
  1. // Copyright (c) 2020 Shivaram Lingamneni <slingamn@cs.stanford.edu>
  2. // released under the MIT license
  3. package utils
  4. import (
  5. "bytes"
  6. "regexp"
  7. "regexp/syntax"
  8. )
  9. // yet another glob implementation in Go
  10. func CompileGlob(glob string) (result *regexp.Regexp, err error) {
  11. var buf bytes.Buffer
  12. buf.WriteByte('^')
  13. for _, r := range glob {
  14. switch r {
  15. case '*':
  16. buf.WriteString("(.*)")
  17. case '?':
  18. buf.WriteString("(.)")
  19. case 0xFFFD:
  20. return nil, &syntax.Error{Code: syntax.ErrInvalidUTF8, Expr: glob}
  21. default:
  22. buf.WriteString(regexp.QuoteMeta(string(r)))
  23. }
  24. }
  25. buf.WriteByte('$')
  26. return regexp.Compile(buf.String())
  27. }