Search code examples
goglob

golang glob matches wrong segment path


I am trying to verify that certain file paths are "valid", using a glob pattern.
For example, I expect the following pattern: '/Users/*/path/to/program'
to match with: '/Users/username/path/to/program'
but to not match with: '/Users/username/another/path/to/program'
Unfortunately, the following code prints "true" which I think is wrong?

package main

import (
    "fmt"

    "github.com/gobwas/glob"
)

func main() {
    ptrn := "/users/*/path/to/program.exe"
    filep := "/users/hedwig/another/path/to/program.exe"
    g := glob.MustCompile(ptrn)    

    fmt.Println(g.Match(filep))
}

Solution

  • You have to set a separator:

    package main
    
    import (
            "fmt"
    
            "github.com/gobwas/glob"
    )
    
    func main() {
            ptrn := "/users/*/path/to/program.exe"
            filep := "/users/hedwig/another/path/to/program.exe"
    
            g := glob.MustCompile(ptrn, '/')
            fmt.Println(g.Match(filep))
    }
    

    As described in the documentation:

    // Compile creates Glob for given pattern and strings (if any present after pattern) as separators.
    // The pattern syntax is:
    //
    //    pattern:
    //        { term }
    //
    //    term:
    //        `*`         matches any sequence of non-separator characters