Documentation ¶
Overview ¶
Package pattern allows working with shell pattern matching notation, also known as wildcards or globbing.
For reference, see https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func HasMeta ¶
HasMeta returns whether a string contains any unescaped pattern metacharacters: '*', '?', or '['. When the function returns false, the given pattern can only match at most one string.
For example, HasMeta(`foo\*bar`) returns false, but HasMeta(`foo*bar`) returns true.
This can be useful to avoid extra work, like TranslatePattern. Note that this function cannot be used to avoid QuotePattern, as backslashes are quoted by that function but ignored here.
func QuoteMeta ¶
QuoteMeta returns a string that quotes all pattern metacharacters in the given text. The returned string is a pattern that matches the literal text.
For example, QuoteMeta(`foo*bar?`) returns `foo\*bar\?`.
Example ¶
package main import ( "fmt" "regexp" "github.com/MerSna/sh/v4/pattern" ) func main() { pat := "foo?bar*" const mode = 0 fmt.Println(pat) quoted := pattern.QuoteMeta(pat, mode) fmt.Println(quoted) expr, err := pattern.Regexp(quoted, mode) if err != nil { return } rx := regexp.MustCompile(expr) fmt.Println(rx.MatchString("foo bar baz")) fmt.Println(rx.MatchString("foo?bar*")) }
Output: foo?bar* foo\?bar\* false true
func Regexp ¶
Regexp turns a shell pattern into a regular expression that can be used with regexp.Compile. It will return an error if the input pattern was incorrect. Otherwise, the returned expression can be passed to regexp.MustCompile.
For example, Regexp(`foo*bar?`, true) returns `foo.*bar.`.
Note that this function (and QuoteMeta) should not be directly used with file paths if Windows is supported, as the path separator on that platform is the same character as the escaping character for shell patterns.
Example ¶
package main import ( "fmt" "regexp" "github.com/MerSna/sh/v4/pattern" ) func main() { pat := "foo?bar*" fmt.Println(pat) expr, err := pattern.Regexp(pat, 0) if err != nil { return } fmt.Println(expr) rx := regexp.MustCompile(expr) fmt.Println(rx.MatchString("foo bar baz")) fmt.Println(rx.MatchString("foobarbaz")) }
Output: foo?bar* foo.bar.* true false