glob

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 5 Imported by: 5 modules, 4 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

glob

Package glob provides glob wildcard matching for Go, and is a fork of the github.com/gobwas/glob package.

The fork has the syntax of the shells: bracket expressions with named classes such as [[:alpha:]], the extended groups of bash such as @(a|b) and !(a), and brace sequences such as {1..10}. It has options to match without regard to case and to give ** the meaning of the globstar of a shell, and the types Path and Host. It depends on the standard library alone.

A match takes time linear in the length of the input, so a glob is safe to match against input that you do not trust. A group of bash that repeats a pattern with no most length, such as +(*a), can take quadratic time. A match of most patterns does not allocate.

Unit Tests Go Reference Releases Discord Discussion

Install

$ go get github.com/kenshaw/glob

Example

The package can be used like the following:

import "github.com/kenshaw/glob"

g, err := glob.Compile(`test*`)
if err != nil {
    /* ... */
}
fmt.Println(g.Match("test_file.txt"))

// Output:
// true

See the package examples for more examples on using glob.

Options go to CompileWith:

g, err := glob.CompileWith(`*.GO`, glob.WithFold())
// g.Match("main.go") == true

p, err := glob.CompilePath(`src/**/*.go`)
// p.Match("src/main.go") == true

h, err := glob.CompileHost(`*.example.com`)
// h.Match("WWW.Example.COM.") == true

A struct field of type glob.Glob, glob.Path or glob.Host unmarshals from a pattern in JSON, YAML or any other format of text.

Syntax

Syntax is meant to be compatible with standard wildcards (as used in Bash or other shells). Additionally, glob supports the "super star" (**) pattern, traversing path separators. A ** does not consume the separator next to it, so a/**/b with the separator / does not match a/b. The option WithGlobstar, and the type Path, give **/ the meaning of the globstar of a shell, which matches no segment too.

Pattern Matches
* any sequence of characters that are not separators
** any sequence of characters, separators too
? one character that is not a separator
[abc], [a-z0-9_] one character of the class
[!a-z], [^a-z] one character not in the class
[[:alpha:]] one character of a named class: alnum, alpha, ascii, blank, cntrl, digit, graph, lower, print, punct, space, upper, word, xdigit
{a,b,c} one of the patterns
{1..10}, {01..10..2}, {a..e} one item of the sequence
?(a|b), *(a|b), +(a|b), @(a|b) zero or one, zero or more, one or more, or exactly one of the patterns
!(a|b) any sequence of characters that are not separators, that none of the patterns matches
\c the character c

A pattern that is not complete, such as a{b or [a, is an error. docs/SYNTAX.md holds every rule and edge case, and how other implementations differ.

Some examples:

Pattern Test Match
[a-z][!a-x]*cat*[h][!b]*eyes* my cat has very bright eyes true
[a-z][!a-x]*cat*[h][!b]*eyes* my dog has very bright eyes false
https://*.google.* https://account.google.com true
https://*.google.* https://google.com false
{https://*.google.*,*yandex.*,*yahoo.*,*mail.ru} http://yahoo.com true
{https://*.google.*,*yandex.*,*yahoo.*,*mail.ru} http://google.com false
{https://*example.com,http://exclude.example.com} https://safe.example.com true
{https://*example.com,http://exclude.example.com} http://safe.example.com false
abc* abcdef true
abc* af false
*def abcdef true
*def af false
ab*ef abcdef true
ab*ef af false

Contributing

CONTRIBUTING.md holds the commands that build and test the package. docs/UPSTREAM.md holds how the fork follows upstream, and docs/decisions/ holds every decision.

Documentation

Overview

Package glob provides glob matching.

Example
package main

import (
	"fmt"

	"github.com/kenshaw/glob"
)

func main() {
	// create simple glob
	g1 := glob.Must("*.github.com")
	fmt.Println(g1.Matcher)
	fmt.Println(g1.Match("api.github.com")) // true

	// quote meta characters and then create simple glob
	g2 := glob.Must(glob.Quote("*.github.com"))
	fmt.Println(g2.Matcher)
	fmt.Println(g2.Match("*.github.com")) // true

	// create new glob with set of delimiters as ["."]
	g3 := glob.Must("api.*.com", '.')
	fmt.Println(g3.Matcher)
	fmt.Println(g3.Match("api.github.com")) // true
	fmt.Println(g3.Match("api.gi.hub.com")) // false

	// create new glob with set of delimiters as ["."]
	// but now with super wildcard
	g4 := glob.Must("api.**.com", '.')
	fmt.Println(g4.Matcher)
	fmt.Println(g4.Match("api.github.com")) // true
	fmt.Println(g4.Match("api.gi.hub.com")) // true

	// create glob with single symbol wildcard
	g5 := glob.Must("?at")
	fmt.Println(g5.Matcher)
	fmt.Println(g5.Match("cat")) // true
	fmt.Println(g5.Match("fat")) // true
	fmt.Println(g5.Match("at"))  // false

	// create glob with single symbol wildcard and delimiters ['f']
	g6 := glob.Must("?at", 'f')
	fmt.Println(g6.Matcher)
	fmt.Println(g6.Match("cat")) // true
	fmt.Println(g6.Match("fat")) // false
	fmt.Println(g6.Match("at"))  // false

	// create glob with character-list matchers
	g7 := glob.Must("[abc]at")
	fmt.Println(g7.Matcher)
	fmt.Println(g7.Match("cat")) // true
	fmt.Println(g7.Match("bat")) // true
	fmt.Println(g7.Match("fat")) // false
	fmt.Println(g7.Match("at"))  // false

	// create glob with character-list matchers
	g8 := glob.Must("[!abc]at")
	fmt.Println(g8.Matcher)
	fmt.Println(g8.Match("cat")) // false
	fmt.Println(g8.Match("bat")) // false
	fmt.Println(g8.Match("fat")) // true
	fmt.Println(g8.Match("at"))  // false

	// create glob with character-range matchers
	g9 := glob.Must("[a-c]at")
	fmt.Println(g9.Matcher)
	fmt.Println(g9.Match("cat")) // true
	fmt.Println(g9.Match("bat")) // true
	fmt.Println(g9.Match("fat")) // false
	fmt.Println(g9.Match("at"))  // false

	// create glob with character-range matchers
	g10 := glob.Must("[!a-c]at")
	fmt.Println(g10.Matcher)
	fmt.Println(g10.Match("cat")) // false
	fmt.Println(g10.Match("bat")) // false
	fmt.Println(g10.Match("fat")) // true
	fmt.Println(g10.Match("at"))  // false

	// create glob with pattern-alternatives list
	g11 := glob.Must("{cat,bat,[fr]at}")
	fmt.Println(g11.Matcher)
	fmt.Println(g11.Match("cat"))  // true
	fmt.Println(g11.Match("bat"))  // true
	fmt.Println(g11.Match("fat"))  // true
	fmt.Println(g11.Match("rat"))  // true
	fmt.Println(g11.Match("at"))   // false
	fmt.Println(g11.Match("zat"))  // false
	fmt.Println(g11.Match("frat")) // false

}
Output:
<suffix:.github.com>
true
<text:`*.github.com`>
true
<btree:[<nothing><-<text:`api.`>-><btree:[<any:![.]><-<text:`.com`>-><nothing>]>]>
true
false
<prefix_suffix:[api.,.com]>
true
true
<row_3:[<single> <text:`at`>]>
true
true
false
<row_3:[<single:![f]> <text:`at`>]>
true
false
false
<row_3:[<list:[abc]> <text:`at`>]>
true
true
false
false
<row_3:[<list:![abc]> <text:`at`>]>
false
false
true
false
<row_3:[<range:[a,c]> <text:`at`>]>
true
true
false
false
<row_3:[<range:![a,c]> <text:`at`>]>
false
false
true
false
<indexed_any_of:[[<text:`cat`> <text:`bat`> <row_3:[<list:[fr]> <text:`at`>]>]]>
true
true
true
true
false
false
false
Example (Extended)
package main

import (
	"fmt"

	"github.com/kenshaw/glob"
)

func main() {
	for _, pattern := range []string{
		"[[:upper:]]*",
		"file{01..03}.txt",
		"@(foo|bar).txt",
		"!(*.go)",
	} {
		g := glob.Must(pattern)
		fmt.Println(pattern, g.Match("Readme"), g.Match("file02.txt"), g.Match("bar.txt"), g.Match("main.go"))
	}
}
Output:
[[:upper:]]* true false false false
file{01..03}.txt false true false false
@(foo|bar).txt false false true false
!(*.go) true true true false

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Quote

func Quote(s string) string

Quote returns a string that escapes each special character of the syntax in s. For example, Quote(`{foo*}`) returns `\{foo\*\}`. A glob compiled from the result matches s and nothing else.

Types

type Glob

type Glob struct {
	syntax.Matcher
	// contains filtered or unexported fields
}

Glob matches glob patterns.

func Compile

func Compile(pattern string, separators ...rune) (*Glob, error)

Compile creates a Glob for given pattern and strings (if any present after pattern) as separators. It is the same as CompileWith with the option WithSeparators. The pattern syntax is:

pattern:
    { term }

term:
    `*`         matches any sequence of non-separator characters
    `**`        matches any sequence of characters
    `?`         matches any single non-separator character
    `[` [ `!` | `^` ] { class-item } `]`
                character class (must be non-empty)
    `{` pattern-list `}`
                pattern alternatives
    `{` lo `..` hi [ `..` step ] `}`
                a sequence of numbers or of letters, as in {1..10},
                {01..10..2} or {a..e}
    `?(` ext-list `)`
                matches zero or one of the patterns
    `*(` ext-list `)`
                matches zero or more of the patterns
    `+(` ext-list `)`
                matches one or more of the patterns
    `@(` ext-list `)`
                matches exactly one of the patterns
    `!(` ext-list `)`
                matches any sequence of non-separator characters that
                none of the patterns matches
    c           matches character c (c != `*`, `**`, `?`, `\`, `[`, `{`, `}`)
    `\` c       matches character c

class-item:
    c           matches character c (c != `\`, `-`, `]`)
    `\` c       matches character c
    lo `-` hi   matches character c for lo <= c <= hi
    `[:` name `:]`
                matches a character of the named class: alnum, alpha,
                ascii, blank, cntrl, digit, graph, lower, print, punct,
                space, upper, word or xdigit
    `[=` c `=]` matches character c
    `[.` c `.]` matches character c

pattern-list:
    pattern { `,` pattern }
                comma-separated (without spaces) patterns

ext-list:
    pattern { `|` pattern }
                patterns separated by a vertical bar

A `]` that is the first character of a class, after an optional `!` or `^`, is a character of the class, and so is a `-` that is first or last.

func CompileWith added in v0.2.0

func CompileWith(pattern string, opts ...Option) (*Glob, error)

CompileWith creates a Glob for the pattern with the options. Compile describes the syntax of the pattern.

Example
package main

import (
	"fmt"

	"github.com/kenshaw/glob"
)

func main() {
	g, err := glob.CompileWith("*.{go,mod}", glob.WithFold())
	if err != nil {
		panic(err)
	}
	fmt.Println(g.Match("MAIN.GO"))
	fmt.Println(g.Match("go.sum"))
}
Output:
true
false

func Must

func Must(pattern string, separators ...rune) *Glob

Must is the same as Compile, except that if Compile returns error, this will panic.

func New

func New(opts ...Option) *Glob

New creates a new, empty glob with the options. Glob.UnmarshalText compiles a pattern with these options.

func (Glob) MarshalText

func (g Glob) MarshalText() ([]byte, error)

MarshalText satisfies the encoding.TextMarshaler interface. It has a value receiver, so a struct field of type Glob marshals as its pattern.

func (*Glob) Match added in v0.2.0

func (g *Glob) Match(s string) bool

Match reports whether the glob matches s. A glob that has no pattern, such as the zero Glob or a glob from New, matches nothing.

func (*Glob) MatchBytes added in v0.2.0

func (g *Glob) MatchBytes(b []byte) bool

MatchBytes reports whether the glob matches b. It does not copy b.

func (*Glob) Separators added in v0.2.0

func (g *Glob) Separators() []rune

Separators returns the separators of the glob.

func (Glob) String

func (g Glob) String() string

String satisfies the fmt.Stringer interface.

func (*Glob) UnmarshalText

func (g *Glob) UnmarshalText(buf []byte) error

UnmarshalText satisfies the encoding.TextUnmarshaler interface. It compiles the text with the options of the glob. See New.

type Host added in v0.2.0

type Host struct {
	Glob
}

Host is a glob that matches host names. Its separator is `.`, and it matches without regard to case. It ignores one dot at the end of a name, so the name example.com. matches as example.com does.

func CompileHost added in v0.2.0

func CompileHost(pattern string, opts ...Option) (*Host, error)

CompileHost creates a Host for the pattern. The options follow the options of a host.

Example
package main

import (
	"fmt"

	"github.com/kenshaw/glob"
)

func main() {
	h, err := glob.CompileHost("{,*.}example.com")
	if err != nil {
		panic(err)
	}
	fmt.Println(h.Match("example.com"))
	fmt.Println(h.Match("WWW.Example.COM."))
	fmt.Println(h.Match("a.b.example.com"))
}
Output:
true
true
false

func (*Host) Match added in v0.2.0

func (h *Host) Match(name string) bool

Match reports whether the host matches name.

func (*Host) MatchBytes added in v0.2.0

func (h *Host) MatchBytes(b []byte) bool

MatchBytes reports whether the host matches b. It does not copy b, unless b holds an upper case letter.

func (*Host) UnmarshalText added in v0.2.0

func (h *Host) UnmarshalText(buf []byte) error

UnmarshalText satisfies the encoding.TextUnmarshaler interface.

type Option added in v0.2.0

type Option func(*options)

Option is an option of CompileWith and New.

func WithFold added in v0.2.0

func WithFold() Option

WithFold is an option to match without regard to case, as strings.EqualFold compares.

func WithGlobstar added in v0.2.0

func WithGlobstar() Option

WithGlobstar is an option to make a `**` that is a whole segment also match no segment at all, as the globstar of a shell does. With the separator `/`, the pattern a/**/b then matches a/b as well as a/x/b.

func WithSeparators added in v0.2.0

func WithSeparators(separators ...rune) Option

WithSeparators is an option to set the separators. A `*` or a `?` does not match a separator, and a `**` does.

type Path added in v0.2.0

type Path struct {
	Glob
}

Path is a glob that matches slash-separated paths. Its separator is `/`, and a `**` that is a whole segment matches no segment too. See WithGlobstar.

func CompilePath added in v0.2.0

func CompilePath(pattern string, opts ...Option) (*Path, error)

CompilePath creates a Path for the pattern. The options follow the options of a path.

Example
package main

import (
	"fmt"

	"github.com/kenshaw/glob"
)

func main() {
	p, err := glob.CompilePath("src/**/*.go")
	if err != nil {
		panic(err)
	}
	fmt.Println(p.Match("src/main.go"))
	fmt.Println(p.Match("src/a/b/main.go"))
	fmt.Println(p.Match("src/a/b/main.c"))
}
Output:
true
true
false

func (*Path) Match added in v0.2.0

func (p *Path) Match(name string) bool

Match reports whether the path matches name. It changes each separator of the operating system in name to a slash first. See filepath.ToSlash.

func (*Path) MatchBytes added in v0.2.0

func (p *Path) MatchBytes(b []byte) bool

MatchBytes reports whether the path matches b. It does not copy b, unless the separator of the operating system is not a slash.

func (*Path) UnmarshalText added in v0.2.0

func (p *Path) UnmarshalText(buf []byte) error

UnmarshalText satisfies the encoding.TextUnmarshaler interface.

Directories

Path Synopsis
cmd
globdraw command
globtest command
Package syntax holds the lexer, the parser, the tree and the matchers of a glob pattern.
Package syntax holds the lexer, the parser, the tree and the matchers of a glob pattern.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址