go - golang glob matches wrong segment path - Stack Overflow

admin2025-04-18  4

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/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))
}

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))
}
Share Improve this question asked Jan 29 at 15:25 Amit ShaniAmit Shani 4051 gold badge4 silver badges11 bronze badges 1
  • 1 Why are you using github.com/gobwas/glob? If it doesn’t fit your needs: use a different glob package or file an issue. This has nothing to do with Go. – Volker Commented Jan 29 at 16:26
Add a comment  | 

1 Answer 1

Reset to default 1

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
转载请注明原文地址:http://anycun.com/QandA/1744956381a90003.html