Shell Patterns With filepath.Match

Test names against shell style patterns with filepath.Match, which matches single path elements only and reports malformed brackets as ErrBadPattern.

GoCli Tooling

Code

gosnippet
29 lines
package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	names := []string{"app.log", "app.log.1", "data-1.csv", "data-12.csv", "notes.txt"}

	for _, pattern := range []string{"*.log", "data-?.csv"} {
		fmt.Println("pattern:", pattern)
		for _, name := range names {
			ok, err := filepath.Match(pattern, name)
			if err != nil {
				panic(err)
			}
			fmt.Printf("  %-12s %v\n", name, ok)
		}
	}

	// 语法错误:未闭合的 [ 返回 ErrBadPattern,而不是静默判为不匹配
	_, err := filepath.Match("data-[0-9.csv", "data-1.csv")
	fmt.Println("bad pattern detected:", err == filepath.ErrBadPattern, err)

	// Match 只作用于单个路径元素:* 不跨分隔符,也不认识 **
	cross, err := filepath.Match("dir/*.go", "dir/sub/main.go")
	fmt.Println("crosses separator:", cross, err)
}

How the snippet works

Every runnable line is contained in the function main.

Iteration happens inside for _, pattern := range []string{"*.log", "data-?.csv"} — everything outside it runs once. Failure handling is panic(err): 1 checkpoint abort the program at the point a problem is detected.

Caveats

  • Nothing to install: the snippet stays inside the standard library.
  • panic(err) guards exactly one call site — a malformed pattern from filepath.Match inside the loop. The two later checks (bad pattern detected:, crosses separator:) capture their errors and print them instead, because ErrBadPattern and a refused cross-separator match are expected outcomes here, not crashes.

Applying it

The signature doing the main work is func main()

Each step the file takes is announced in the output: pattern:, bad pattern detected:, crosses separator:.

Statements that matter most here

for _, pattern := range []string{"*.log", "data-?.csv"} {
fmt.Println("pattern:", pattern)
for _, name := range names {
ok, err := filepath.Match(pattern, name)
if err != nil {
panic(err)
}
fmt.Printf("  %-12s %v\n", name, ok)
}
}

Interactive Tools for This Topic

FAQ

How does the code signal failure?
Through `panic(err)` — the 1 checkpoints test `err` and abort the run on the first non-nil one.
What does Shell Patterns With filepath.Match print when run?
No setup needed: run the file and look for labeled lines like `pattern:`, `bad pattern detected:`, `crosses separator:` in the output.